channel.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import os
  2. import pathlib
  3. from urllib.parse import urljoin
  4. from lxml.html import etree, HtmlElement
  5. from common.tools import sha1, detect_encoding
  6. from crawler.analysis import TimeExtractor
  7. from crawler.defaults import PAGE_TEXTS, LOGIN_TEXTS, NAV_TEXTS
  8. from crawler.download import Downloader
  9. from crawler.utils import (
  10. element2html,
  11. html2element,
  12. iter_node,
  13. drop_tag,
  14. remove_node,
  15. pre_parse,
  16. is_empty_element,
  17. is_title,
  18. )
  19. _base_path = pathlib.Path(__file__).parent
  20. def analysis(origin_lst, target_lst):
  21. results = []
  22. for target_ in target_lst:
  23. source: str = target_['contenthtml']
  24. _c = 0
  25. for item in origin_lst:
  26. href, channel = item['href'], item['channel']
  27. if source.count(channel) > 0 or source.count(href) > 0:
  28. _c += 1
  29. if _c > 0:
  30. results.append({
  31. 'similarity': _c,
  32. 'contenthtml': source,
  33. 'depth': target_['depth']
  34. })
  35. results = sorted(results, key=lambda x: x['similarity'], reverse=True)
  36. _t = max(results, key=lambda dic: dic['depth'])
  37. return _t
  38. def extract_text(node: HtmlElement):
  39. text = (node.text or node.tail or node.xpath('string(.)'))
  40. return "".join(f"{text}".split())
  41. def tag_date_total(node: HtmlElement, tag=None):
  42. count = 0
  43. # 先辈节点与目标节点名称相同并且包含时间文本的个数
  44. contains_date_nodes = []
  45. if tag is not None:
  46. descendants = list(node.iterdescendants(tag))
  47. else:
  48. descendants = list(node.iterdescendants())
  49. for descendant in descendants:
  50. pt = TimeExtractor().extractor(descendant)
  51. children = len(list(descendant.iterchildren())) > 0
  52. if pt != '' and not children and descendant not in contains_date_nodes:
  53. contains_date_nodes.append(descendant)
  54. count += 1
  55. return count
  56. def remove_ancestors_date_tag(node: HtmlElement):
  57. # tag = node.tag.lower() # TODO 是否一定需要后裔节点的类型
  58. prev_node = node
  59. # 情况1: 先辈节点下直接放置全部的时间节点,直接删除
  60. remove_count = 0
  61. for ancestor in node.iterancestors():
  62. is_remove = False
  63. total = tag_date_total(ancestor)
  64. # print("ancestors_date_tag >>> ", ancestor.tag, ancestor.attrib, total)
  65. if total > 3:
  66. # 情况2: ancestor节点下面不直接放置全部的时间节点;
  67. # 首先查询出时间文本大于3及以上的节点,此时直接删除ancestor节点,会导致
  68. # ancestor节点边界变大,包括不想期望保留节点一起被删除。此处遍历查询prev_node
  69. # 兄弟节点(ancestor后裔节点)寻找时间文本大于3及以上的兄弟节点,若不存
  70. # 时间文本大于3及以上的情况,此时再处理ancestor节点,达到增大边界效果,删除即可
  71. for sibling in prev_node.itersiblings():
  72. sibling_tag_date_total = tag_date_total(sibling)
  73. if sibling_tag_date_total > 3:
  74. remove_node(sibling)
  75. is_remove = True
  76. # print("remove sibling tag >>> ", sibling.tag, sibling.attrib, )
  77. # 查询出时间文本大于3及以上,若prev_node的没有兄弟节点,此时直接删除该ancestor
  78. if not is_remove:
  79. remove_node(ancestor)
  80. # print("remove ancestor tag >>> ", ancestor.tag, ancestor.attrib, )
  81. is_remove = True
  82. elif 1 < total <= 2:
  83. # 逐条删除(查询出时间文本条数,从子节点边界范围进行查询、剔除,防止)
  84. for child in ancestor.iterchildren():
  85. child_tag_date_total = tag_date_total(child)
  86. if child_tag_date_total > 0:
  87. remove_node(child)
  88. # print("remove child tag >>> ", child.tag, child.attrib, )
  89. is_remove = True
  90. if not is_remove:
  91. remove_node(ancestor)
  92. # print("remove ancestor tag >>> ", ancestor.tag, ancestor.attrib, )
  93. is_remove = True
  94. else:
  95. # 保存上一次查询的先辈节点(时间文本小于等于3)
  96. prev_node = ancestor
  97. if is_remove:
  98. remove_count += 1
  99. return True if remove_count > 0 else False
  100. def show_html(page, *, file=None, bash_url=None):
  101. if bash_url is None:
  102. bash_url = ''
  103. if isinstance(page, HtmlElement):
  104. source = element2html(page)
  105. elif isinstance(page, bytes):
  106. source = page.decode(detect_encoding(page), 'surrogatepass')
  107. else:
  108. source = page
  109. if file is None:
  110. dirname = 'html'
  111. os.makedirs(dirname, mode=0o777, exist_ok=True)
  112. file = f'{dirname}/{sha1(bash_url)}.html'
  113. else:
  114. file = file
  115. with open(file, 'w') as fp:
  116. fp.write(source)
  117. def trim_node(element: HtmlElement):
  118. """
  119. 整理节点 (body子节点更新为div,在更新过程中子节点会合并文本)
  120. :param element:
  121. :return:
  122. """
  123. children = element.xpath('/html/body/child::*')
  124. for child in children:
  125. for node, _ in iter_node(child):
  126. # print('trim_node >>> ', node.tag, node.attrib)
  127. if node.tag.lower() == 'div':
  128. break
  129. drop_tag(node)
  130. return element
  131. def strip_node(element: HtmlElement):
  132. """
  133. 剔除节点,若不是标签a且无时间文本,关键词标题,标签a个数,移除或者剔除
  134. :param element:
  135. :return:
  136. """
  137. for node, _ in iter_node(element):
  138. # 节点文本(剔除空白、换行、回车符号)
  139. text = "".join("".join(node.xpath('./text()')).split())
  140. # 删除掉没有文本、发布时间、发布标题、href属性的节点及父节点
  141. if node.tag.lower() != 'a':
  142. # 关键词文本
  143. non_title = is_title(text) is False
  144. # 后裔a节点数量
  145. total_tag_gt_0 = len(list(node.iterdescendants('a'))) == 0
  146. # 时间文本
  147. publish_time = TimeExtractor().extractor(node)
  148. # print('>>> ', node.tag, node.attrib, text)
  149. if non_title and total_tag_gt_0 and publish_time == '':
  150. # print('strip_node >>> ', node.tag, node.attrib, text)
  151. parent = node.getparent()
  152. if parent is not None and parent.tag.lower() == 'a':
  153. etree.strip_tags(parent, node.tag)
  154. elif parent is not None and parent.tag.lower() == 'td':
  155. remove_node(parent)
  156. else:
  157. remove_node(node)
  158. def remove_nav_node(element: HtmlElement):
  159. for node, _ in iter_node(element):
  160. text = extract_text(node)
  161. # print('nav_node >>> ', node.tag, text)
  162. # (板块文本|页脚文本|导航文本)
  163. for item in NAV_TEXTS:
  164. if item in text:
  165. remove_node(node)
  166. # 登录标签
  167. if text in LOGIN_TEXTS:
  168. remove_node(node)
  169. # 翻页标签栏
  170. if text in PAGE_TEXTS:
  171. tag = node.tag.lower()
  172. siblings = list(node.itersiblings(tag))
  173. # 通过查询相同标签兄弟节点,兄弟节点包含在一个先辈节点内;翻页标签不包含在同一先辈节点
  174. if len(siblings) > 3 and node.tag.lower() == tag:
  175. remove_node(node.getparent())
  176. else:
  177. for ancestor in node.iterancestors():
  178. # 先辈节点包含两个以上同类节点,则认为该先辈节点包含全部想要删除标签
  179. if len(list(ancestor.iterdescendants(tag))) > 2:
  180. remove_node(ancestor)
  181. break
  182. # 位置标签
  183. if '位置' in text:
  184. remove_node(node)
  185. def remove_date_node(element: HtmlElement):
  186. retrieve = False
  187. for node, _ in iter_node(element):
  188. if retrieve:
  189. break
  190. publish_time = TimeExtractor().extractor(node)
  191. # print('date_node >>> ', node.tag, node.attrib, publish_time)
  192. # 首先找拥有时间文本最深层级节点(拥有时间文本,不存在子节点)
  193. if publish_time != '' and len(list(node.iterchildren())) == 0:
  194. # print("date_node >>> ", node.tag, node.attrib, len(list(node.itersiblings())))
  195. # 时间文本有可能来自兄弟节点,而不是自身
  196. if len(list(node.itersiblings())) > 0:
  197. # 存在多个兄弟节点,所以通过分析共同的父节点
  198. parent = node.getparent()
  199. # 统计父节点的拥有时间文本的后裔节点个数
  200. total = tag_date_total(parent)
  201. if total > 3:
  202. # 简单场景:仅仅单个兄弟节点拥有时间文本(发布时间)
  203. remove_node(parent)
  204. else:
  205. # 复杂场景:多个兄弟节点拥有时间文本(开始时间,截止时间...)
  206. # print("parent_date_node >>> ", parent.tag, parent.attrib, len(list(parent.itersiblings())))
  207. # 从父节点开始,查询且删除先辈节点中拥有时间文本的先辈节点
  208. retrieve = remove_ancestors_date_tag(parent)
  209. else:
  210. # 情况2:无兄弟节点,从自身开始,查询且删除先辈节点中拥有时间文本的先辈节点
  211. retrieve = remove_ancestors_date_tag(node)
  212. def clean_node(element):
  213. for node, _ in iter_node(element):
  214. if is_empty_element(node):
  215. # print(' clean_node >>> ', node.tag, node.attrib, extract_text(node))
  216. remove_node(node)
  217. if node.tag.lower() == 'a' and list(node.iterchildren()):
  218. # 剔除a标签包含的单个或多个短语标签、文本标签,保留内部文本
  219. for child in node.iterchildren():
  220. etree.strip_tags(node, child.tag)
  221. def extract_data(source, base_url):
  222. element = html2element(source)
  223. children = element.xpath('/html/body/child::*')
  224. result = {}
  225. for index, child in enumerate(children):
  226. data = []
  227. for node in child.iterdescendants('a'):
  228. title = extract_text(node)
  229. href = node.attrib.get('href')
  230. href = urljoin(base_url, href)
  231. if is_title(title) and len(title) <= 15:
  232. item = (title, href)
  233. data.append(item)
  234. key = "{}_{}".format(child.tag.lower(), index)
  235. result[key] = data
  236. print(result)
  237. for key, items in result.items():
  238. print(f"=============== {base_url} && {key} ===============")
  239. for val in items:
  240. print(val)
  241. print()
  242. return result
  243. def process_page(source):
  244. element = html2element(source)
  245. # web网页预处理(web页面去噪,会改变原始dom结构)
  246. element = pre_parse(element)
  247. # show_html(element, file='2预处理.html')
  248. # 整理节点
  249. element = trim_node(element)
  250. # show_html(element, file='3整理body节点.html')
  251. # 剔除节点
  252. strip_node(element)
  253. # show_html(element, file='4剔除节点.html')
  254. # 删除导航节点
  255. remove_nav_node(element)
  256. # show_html(element, file='5删除导航条.html')
  257. # 删除时间节点
  258. remove_date_node(element)
  259. # show_html(element, file='6删除时间块.html')
  260. # 清理节点
  261. clean_node(element)
  262. # show_html(element, file='7清理dom.html')
  263. return element2html(element)
  264. def bfs(response, base_url):
  265. source = response.text
  266. # show_html(source, file='1原始页.html')
  267. if len(source) == 0:
  268. return {}
  269. source = process_page(source)
  270. items = extract_data(source, base_url)
  271. return items