utils.py 8.0 KB

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