【问题标题】:Access Chrome DOM tree with python使用 python 访问 Chrome DOM 树
【发布时间】:2012-09-21 13:44:01
【问题描述】:

使用 Chrome DevTools,您可以查看页面的 DOM 树。有没有办法使用 python 访问和拉出那棵树?

【问题讨论】:

  • 为什么要使用 Python?您可以使用 javascript 和 jquery 等客户端工具来访问 dom。
  • @voscausa -- 我想用python解析和分析动态内容。

标签: python google-chrome dom


【解决方案1】:

我发现最好的方法是使用selenium.webdriver:

import selenium.webdriver as webdriver
import lxml.html as lh
import lxml.html.clean as clean

browser = webdriver.Chrome() # Get local session of Chrome
browser.get("http://www.webpage.com") # Load page

content=browser.page_source
cleaner=clean.Cleaner()
content=cleaner.clean_html(content) 
doc=lh.fromstring(content)

doc 获取 DOM 为 lxml.html.HtmlElement

【讨论】:

【解决方案2】:

你用过 BeautifulSoup 库吗?本教程的这一部分可能会回答您的问题。 http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#The解析树

然后,你还需要导入Requests库。

from BeautifulSoup import BeautifulSoup
import requests
url = 'http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html'
page = requests.get(url)
soup = BeautifulSoup(page.content)
print soup 

【讨论】:

  • @ michellesun -- 谢谢你的回答,但不幸的是,这只会让我得到没有 javascript 提供的动态内容的 html。
  • @root:如果动态生成的内容很关键,您应该将该要求添加到您的问题中。一定要描述它的生成时间和方式——如果它需要用户交互才能出现,这会大大扩展它的范围。
  • @ Shog9 -- 问题是关于访问 Chrome dom 树。我觉得没有必要说明我这样做的原因,因为它已经足够具体了。使用 BS 访问 html 页面与我要求的有所不同。此外,cmets 中还提到了动态内容。
猜你喜欢
  • 2014-07-18
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多