通过XPath解析HTML
在.Net中,我发现了一个很棒的库,叫做HtmlAgilityPack,它可以让你轻松地用XPath解析那些格式不太规范的HTML。我在我的.Net网站上用了好几年这个库,但在我的Python、Ruby和其他项目中,我不得不忍受一些更麻烦的库。有没有人知道其他语言中有没有类似的库呢?
7 个回答
7
我用过的最稳定的结果是使用lxml.html的soupparser。你需要先安装python-lxml和python-beautifulsoup这两个库,然后你就可以这样做:
from lxml.html.soupparser import fromstring
tree = fromstring('<mal form="ed"><html/>here!')
matches = tree.xpath("./mal[@form=ed]")
70
我很惊讶居然没有人提到lxml这个库。它的速度非常快,并且可以在任何支持CPython库的环境中使用。
这里有一个链接,教你如何通过XPATH使用lxml来解析HTML:你可以查看这个教程。
>>> from lxml import etree
>>> doc = '<foo><bar></bar></foo>'
>>> tree = etree.HTML(doc)
>>> r = tree.xpath('/foo/bar')
>>> len(r)
1
>>> r[0].tag
'bar'
>>> r = tree.xpath('bar')
>>> r[0].tag
'bar'
7
在Python中,ElementTidy 可以处理杂乱的标签,并生成一个元素树,这样你就可以使用XPath来查询这些元素。
>>> from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB
>>> tb = TB()
>>> tb.feed("<p>Hello world")
>>> e= tb.close()
>>> e.find(".//{http://www.w3.org/1999/xhtml}p")
<Element {http://www.w3.org/1999/xhtml}p at 264eb8>