utils.py 7.7 KB

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