utils.py 8.2 KB

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