utils.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import re
  2. from html import unescape
  3. from urllib.parse import urlencode, urljoin
  4. from bs4 import BeautifulSoup
  5. from lxml.html import etree, HtmlElement, fromstring, tostring
  6. from urllib3 import get_host
  7. from common.log import logger
  8. from crawler.defaults import (
  9. USELESS_TAG,
  10. USELESS_ATTR,
  11. TAGS_CAN_BE_REMOVE_IF_EMPTY,
  12. KEYWORDS,
  13. )
  14. def err_details(worker):
  15. worker_exception = worker.exception()
  16. if worker_exception:
  17. logger.exception("Worker return exception: {}".format(worker_exception))
  18. return worker
  19. def extract_host(url):
  20. """
  21. # >>> base_url = extract_host('http://192.168.3.207:8080/')
  22. """
  23. _s, _h, _p = get_host(url)
  24. return f"{_s}://{_h}/" if _p is None else f"{_s}://{_h}:{_p}/"
  25. def split_domain(val: str):
  26. if re.match(r'\d+', val) is None:
  27. return re.split(r'[\\.:]', val)
  28. return [val]
  29. def extract_domain(url):
  30. """
  31. # >>> base_url = extract_domain('http://192.168.3.207:8080/')
  32. """
  33. _, host, port = get_host(url)
  34. return f"{host}" if port is None else f"{host}:{port}"
  35. def extract_page_title(source):
  36. element = html2element(source)
  37. nodes = element.xpath('/html/head/title/text()|//title/text()')
  38. if len(nodes) > 1:
  39. return "".join(";".join(nodes).split())
  40. return "".join("".join(nodes).split())
  41. def is_url(url):
  42. """判断url格式畸形与否"""
  43. _regex = re.compile(
  44. r'^(?:http|ftp)s?://' # http:// or https://
  45. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
  46. r'localhost|' # localhost...
  47. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
  48. r'(?::\d+)?' # optional port
  49. r'(?:/?|[/?]\S+)$', re.IGNORECASE)
  50. return re.match(_regex, url) is not None
  51. def is_domain(domain):
  52. _regex = re.compile(
  53. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
  54. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
  55. r'(?::\d+)?', re.IGNORECASE)
  56. return re.match(_regex, domain) is not None
  57. def label_split(val):
  58. # '~`!#$%^&*()_+-=|\';"":/.,?><~·!@#¥%……&*()——+-=“:’;、。,?》{《}】【\n\]\[ '
  59. result = re.split(r'[- _,,\\.|-「」【】??!!/、] *', val)
  60. result = [v for v in result if len(v) > 0]
  61. return result
  62. def get_url(url: str, parameters: dict):
  63. """
  64. 拼接url与所带参数
  65. :param url: 链接
  66. :param parameters: 参数
  67. :return: 拼接后的url
  68. """
  69. _data = '?' + urlencode(parameters)
  70. return urljoin(url, _data)
  71. def clean_html(source: str):
  72. html_str = re.sub(r'<!--[\s\S]*?-->', '', source)
  73. html_str = re.sub(r'<html>|<html [^>]*>|</html>', '', html_str)
  74. html_str = re.sub(r'<head>[\s\S]*?</head>', '', html_str)
  75. html_str = re.sub(r'<script[^<>]*>[\s\S]*?</script>|</script>', '', html_str)
  76. html_str = re.sub(r'<style[^<>]*>[\s\S]*?</style>', '', html_str)
  77. html_str = re.sub(r'<link[^<>]*>[\s\S]*?', '', html_str)
  78. html_str = re.sub(r'<img[^>]*>', '', html_str)
  79. return html_str
  80. def extract_text(source: str):
  81. soup = BeautifulSoup(source, "lxml")
  82. return soup.get_text()
  83. def verify_text(val: str, length=50):
  84. """检查数字、字母、中文的个数"""
  85. if val is None:
  86. return False
  87. sub_pattern = ['<[^>]+>', '[^0-9a-zA-Z\u4e00-\u9fa5]+']
  88. for pattern in sub_pattern:
  89. val = re.sub(pattern, '', val)
  90. # 若文本长度小于指定文本长度(length),表示页面内容无详情内容
  91. if len(val) < length:
  92. '''无效文本'''
  93. return False
  94. '''有效文本'''
  95. return True
  96. def element2html(element: HtmlElement) -> str:
  97. return unescape(tostring(element, encoding="utf-8").decode())
  98. def html2element(source: str, base_url=None) -> HtmlElement:
  99. html_str = re.sub('\ufeff|\xa0|\u3000|\x00', '', source)
  100. html_str = re.sub('<!--[\s\S]*?-->', '', html_str) # 清除注释
  101. html_str = re.sub(r'<style[^<>]*>[\s\S]*?</style>', '', html_str) # 清除样式
  102. html_str = re.sub(r'<script[^<>]*>[\s\S]*?</script>', '', html_str) # 清除js
  103. html_str = re.sub('</?br.*?>', '', html_str)
  104. html_str = re.sub(r'<\?xml.*?>', '', html_str)
  105. html_str = re.sub(r'<[!]DOCTYPE.*?>', '', html_str)
  106. return fromstring(html_str, base_url=base_url)
  107. def iter_node(element: HtmlElement, depth=1):
  108. yield element, depth
  109. depth += 1
  110. for sub_element in element:
  111. if isinstance(sub_element, HtmlElement):
  112. yield from iter_node(sub_element, depth)
  113. # print('退出', depth)
  114. def remove_node(node: HtmlElement):
  115. """
  116. this is a in-place operation, not necessary to return
  117. :param node:
  118. :return:
  119. """
  120. parent = node.getparent()
  121. if parent is not None:
  122. node.drop_tree()
  123. # parent.remove(node)
  124. def drop_tag(node: HtmlElement):
  125. """
  126. only delete the tag, but merge its text to parent.
  127. :param node:
  128. :return:
  129. """
  130. parent = node.getparent()
  131. if parent is not None:
  132. node.drop_tag()
  133. def is_empty_element(node: HtmlElement):
  134. return not node.getchildren() and not node.text
  135. def normalize_node(element: HtmlElement):
  136. etree.strip_elements(element, *USELESS_TAG, with_tail=False)
  137. # 节点预处理,删除节点与更新节点的操作在同一循环发生时,更新节点的操作不会生效,原因:?
  138. # 空节点合并、噪声节点剔除
  139. for node, _ in iter_node(element):
  140. if node.tag.lower() in TAGS_CAN_BE_REMOVE_IF_EMPTY and is_empty_element(node):
  141. remove_node(node)
  142. if node.tag.lower() == 'p':
  143. etree.strip_tags(node, 'span')
  144. etree.strip_tags(node, 'strong')
  145. # if a div tag does not contain any sub node, it could be converted to p node.
  146. if node.tag.lower() == 'div' and not node.getchildren():
  147. node.tag = 'p'
  148. if node.tag.lower() == 'span' and not node.getchildren():
  149. node.tag = 'p'
  150. # remove empty p tag
  151. if node.tag.lower() == 'p' and not node.xpath('.//img'):
  152. if not (node.text and node.text.strip()):
  153. drop_tag(node)
  154. # Delete inline styles
  155. style = node.get('style')
  156. if style:
  157. del node.attrib['style']
  158. # 删除包含干扰属性的节点(完全匹配)
  159. for node, _ in iter_node(element):
  160. attr = (node.get('id') or node.get('class'))
  161. if attr:
  162. if attr.lower() in USELESS_ATTR:
  163. remove_node(node)
  164. break
  165. # # 删除无效节点(模糊匹配)
  166. # for node, _ in iter_node(element):
  167. # attrib = (node.get('id') or node.get('class'))
  168. # if attrib:
  169. # for attr in USELESS_ATTR:
  170. # if re.match(attr, attrib.lower()) is not None:
  171. # remove_node(node)
  172. # break
  173. def pre_parse(element):
  174. normalize_node(element)
  175. return element
  176. def is_title(val: str):
  177. """检查数字、字母、中文的个数"""
  178. for keyword in KEYWORDS:
  179. search = re.search(keyword, val)
  180. if search is not None:
  181. return True
  182. return False