DomAnalysis.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import re
  2. from bs4 import BeautifulSoup
  3. from crawler.analysis.FilterUrl import FilterUrl
  4. class DomAnalysis(FilterUrl):
  5. """
  6. Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
  7. Tag
  8. NavigableString
  9. BeautifulSoup
  10. Comment
  11. """
  12. def __init__(self, dom, base_url):
  13. self.soup = BeautifulSoup(dom, "lxml")
  14. self.url = base_url
  15. self.pattern = re.compile("href=([a-zA-Z0-9'\"+?=.%/_]*)")
  16. def show_html(self):
  17. #https://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html 发现prettify是u字符
  18. print(self.soup.prettify().encode('utf-8', 'ignore'))
  19. def _is_input_with_onclick(self, tag):
  20. return (tag.name == 'input') and (tag.get('type')=='button') and tag.has_attr('onclick')
  21. def get_urls(self, **kwargs):
  22. urls = []
  23. # 静态页面链接解析 和 javascript动态解析
  24. for tag in self.soup.find_all('a'):
  25. if self.judge(tag.get('href'), **kwargs):
  26. urls.append(self.filter(tag.get('href')))
  27. # 自动交互. 这里采用静态解析的思路提取交互式生成的链接
  28. for tag in self.soup.find_all():
  29. if self._is_input_with_onclick(tag):
  30. for item in re.findall(self.pattern, tag.get('onclick')):
  31. if self.judge(self.onclick_filter(item), **kwargs):
  32. urls.append(self.filter(self.onclick_filter(item)))
  33. return urls
  34. def get_items(self, **kwargs):
  35. items = []
  36. def _extract():
  37. name = (tag.text if len(tag.text) != 0 else None or tag.parent.text)
  38. name = "".join(name.split())
  39. if len(name) > 50:
  40. name = "{:.50s}".format(name)
  41. if tag.get('href') is None:
  42. return
  43. try:
  44. href = self.filter(tag.get('href'))
  45. except ValueError:
  46. return
  47. data = {'name': name, 'host': href}
  48. if data not in items:
  49. items.append(data)
  50. for tag in self.soup.find_all('a'):
  51. if self.judge(tag.get('href'), **kwargs):
  52. _extract()
  53. for tag in self.soup.find_all():
  54. if self._is_input_with_onclick(tag):
  55. for item in re.findall(self.pattern, tag.get('onclick')):
  56. if self.judge(self.onclick_filter(item), **kwargs):
  57. _extract()
  58. return items