utils.py 8.1 KB

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