clean_html.py 5.5 KB

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