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