utils.py 8.2 KB

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