clean_html.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import re
  2. __all__ = ['cleaner']
  3. # 独立元素
  4. INDEPENDENT_TAGS = {
  5. '<head>[\s\S]*?</head>': '',
  6. '<html>|<html [^>]*>|</html>': '',
  7. '<body>|<body [^>]*>|</body>': '',
  8. '<meta[^<>]*>|<meta [^<>]*>|<meta[^<>]*>[\s\S]*?</meta>|</meta>': '', # 元数据
  9. '&(nbsp|e[mn]sp|thinsp|zwn?j|#13);': '', # 空格
  10. '\\xa0|\\u3000': '', # 空格
  11. '<!--[\s\S]*?-->': '', # 注释
  12. '<style[^<>]*>[\s\S]*?</style>': '', # 样式
  13. '<script[^<>]*>[\s\S]*?</script>': '', # JavaScript
  14. '<input>': '', # 输入框
  15. '<img[^>]*>': '<br>', # 图片
  16. }
  17. # 行内元素
  18. INLINE_TAGS = {
  19. '<a>|<a [^>]*>|</a>': '', # 超链接
  20. '<link>|<link [^>]*>|</link>': '', # 超链接
  21. '<span>|<span [^>]*>|</span>': '', # span
  22. '<label>|<label [^>]*>|</label>': '<br>', # label
  23. '<font>|<font [^>]*>|</font>': '', # font
  24. 'data:image(.*?) ': '', # 图片base64
  25. }
  26. # 块级元素
  27. BLOCK_TAGS = {
  28. '<div>\s*?</div>':'',
  29. '<h[1-6][^>]*>|</h[1-6]>': '', # 标题
  30. '<p>|<p [^>]*>': '<br>', # 段落
  31. '</p>': '', # 段落
  32. '<div>|<div [^>]*>': '<br>', # 分割 division
  33. '</div>': '', # 分割 division
  34. '<o:p>|<o:p [^>]*>|</o:p>': '' # OFFICE微软WORD段落
  35. }
  36. # 其他
  37. OTHER = {
  38. '<?xml[^>]*>|<?xml [^>]*>|<?xml:.*?>': '',
  39. '<epointform>': '',
  40. '<!doctype html>|<!doctype html [^>]*>': '',
  41. '【关闭】|关闭': '',
  42. '【打印】|打印本页': '',
  43. '【字体:[\s\S]*】': '',
  44. '文章来源:[\u4e00-\u9fa5]+': '',
  45. '浏览次数:.*[<]+': '',
  46. '(责任编辑:.*?)': '',
  47. '分享到[:]': '',
  48. }
  49. # 样式
  50. CSS_STYLE = {
  51. 'style="[\s\S]*?"|style ="[\s\S]*?"': '',
  52. 'bgcolor="[\s\S]*?"|bgcolor ="[\s\S]*?"': '',
  53. 'bordercolor="[\s\S]*?"|bordercolor ="[\s\S]*?"': '',
  54. 'class="[\s\S]*?"|class ="[\s\S]*?"': '',
  55. 'align="[\s\S]*?"|align ="[\s\S]*?"': '',
  56. 'cellpadding="(\d+)"|cellspacing="(\d+)"': '',
  57. }
  58. # 空白符
  59. BLANKS = {
  60. '\n\s*\n': '\n',
  61. '\s*\n\s*': '\n',
  62. '[^\S\n]': ' ',
  63. '\s+': ' ',
  64. }
  65. # css标签集合
  66. TAGS = {'table', 'tr', 'td', 'div', 'span', 'p'}
  67. # css属性集合
  68. ATTRS = {'id', 'class', 'style', 'width'}
  69. def _repair_tag():
  70. """异常的标签组合,用来替换非标准页面的标签"""
  71. _repairs = {}
  72. for tag in TAGS:
  73. for attr in ATTRS:
  74. key = '{}{}'.format(tag, attr)
  75. val = '{} {}'.format(tag, attr)
  76. _repairs[key] = val
  77. return _repairs
  78. def _escape_character(html):
  79. """转义字符"""
  80. html = html.replace('&lt;', '<')
  81. html = html.replace('&gt;', '>')
  82. html = html.replace('&quot;', '"')
  83. html = html.replace('&amp;', '&')
  84. # 不显示输入框边框
  85. html = html.replace('<input', '<input style="border-color: transparent;"')
  86. return html
  87. def _lowercase_tag(html):
  88. """标签归一化处理(全部小写 + 标签修复)"""
  89. tags = re.findall("<[^>]+>", html)
  90. tag_sets = set(tags)
  91. if len(tag_sets) > 10000:
  92. from bs4 import BeautifulSoup
  93. soup = BeautifulSoup(html, "lxml")
  94. html = str(soup.body.next_element)
  95. else:
  96. for tag in tag_sets:
  97. html = html.replace(tag, str(tag).lower())
  98. repair_tags = _repair_tag()
  99. for err, right in repair_tags.items():
  100. html = html.replace(err, right)
  101. return html
  102. def cleaner(html, special=None, completely=False):
  103. """
  104. 数据清洗
  105. :param html: 清洗的页面
  106. :param special: 额外指定页面清洗规则
  107. :param completely: 是否完全清洗页面
  108. :return: 清洗后的页面源码
  109. """
  110. if special is None:
  111. special = {}
  112. OTHER.update(special)
  113. remove_tags = {
  114. **INDEPENDENT_TAGS,
  115. **INLINE_TAGS,
  116. **BLOCK_TAGS,
  117. **OTHER,
  118. **CSS_STYLE,
  119. **BLANKS,
  120. }
  121. html = _lowercase_tag(html)
  122. for tag, repl in remove_tags.items():
  123. html = re.sub(tag, repl, html)
  124. if completely:
  125. html = re.sub(r'<canvas[^<>]*>[\s\S]*?</canvas>', '', html) # 画布
  126. html = re.sub(r'<iframe[^<>]*>[\s\S]*?</iframe>', '', html) # 内框架
  127. html = re.sub('<([^<>\u4e00-\u9fa5]|微软雅黑|宋体|仿宋)+>', '', html)
  128. html = _escape_character(html)
  129. return html