DomAnalysis.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import re
  2. from bs4 import BeautifulSoup
  3. from common.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):
  22. urls = []
  23. # 静态页面链接分析 和 javascript动态解析
  24. for tag in self.soup.find_all('a'):
  25. if self.judge(tag.get('href')):
  26. urls.append(self.filter(tag.get('href')))
  27. # 自动交互. 这里采用静态析的思路提取交互式生成的链接
  28. for tag in self.soup.find_all(self._is_input_with_onclick):
  29. for item in re.findall(self.pattern, tag.get('onclick')):
  30. if self.judge(self.onclick_filter(item)):
  31. urls.append(self.filter(self.onclick_filter(item)))
  32. return urls
  33. def get_items(self):
  34. items = []
  35. # 静态页面链接分析 和 javascript动态解析
  36. for tag in self.soup.find_all('a'):
  37. if self.judge(tag.get('href')):
  38. name = (tag.text if len(tag.text) != 0 else None or tag.parent.text)
  39. href = self.filter(tag.get('href'))
  40. item = {'name': name, 'host': href}
  41. if item not in items:
  42. items.append(item)
  43. # 自动交互. 这里采用静态析的思路提取交互式生成的链接
  44. for tag in self.soup.find_all(self._is_input_with_onclick):
  45. for item in re.findall(self.pattern, tag.get('onclick')):
  46. if self.judge(self.onclick_filter(item)):
  47. name = (tag.text if len(tag.text) != 0 else None or tag.parent.text)
  48. href = self.filter(tag.get('href'))
  49. item = {'name': name, 'host': href}
  50. if item not in items:
  51. items.append(item)
  52. return items