channel.py 12 KB

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