clean_html.py 4.5 KB

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