Skip to main content
 首页 » 编程设计

python之有没有办法解析网站内容的 DOM 树

2025年05月04日8zlslch

<分区>

有一些用于从 xml 内容解析 dom 树的包,例如 https://docs.python.org/2/library/xml.dom.minidom.html .

但我不想定位 xml,只定位 html 网站页面内容。

from htmldom import htmldom 
dom = htmldom.HtmlDom( "http://www.yahoo.com" ).createDom() 
# Find all the links present on a page and prints its "href" value 
a = dom.find( "a" ) 
for link in a: 
    print( link.attr( "href" ) ) 

但是为此我得到了这个错误:

Error while reading url: http://www.yahoo.com 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/usr/local/lib/python2.7/dist-packages/htmldom/htmldom.py", line 333, in createDom 
    raise Exception 
Exception 

看到我已经检查了 BeautifulSoup 但这不是我想要的。 Beautifulsoup 仅适用于 html 页面。如果使用 Javascript 动态加载页面内容,则它会失败。我不想使用 getElementByClassName 和类似方法解析元素。但是 dom.children(0).children(1) 是这样的。

那么有什么方法可以像使用 headless 浏览器、selenium 那样解析整个 DOM 树结构并通过子子和子子来访问目标元素吗?