我正试图让自己摆脱 BeautifulSoup,我喜欢它但似乎(积极地)不受支持。我正在尝试使用 html5lib 和 lxml,但我似乎无法弄清楚如何使用“find”和“findall”运算符。
通过查看 html5lib 的文档,我想出了一个测试程序:
import cStringIO
f = cStringIO.StringIO()
f.write("""
<html>
<body>
<table>
<tr>
<td>one</td>
<td>1</td>
</tr>
<tr>
<td>two</td>
<td>2</td
</tr>
</table>
</body>
</html>
""")
f.seek(0)
import html5lib
from html5lib import treebuilders
from lxml import etree # why?
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("lxml"))
etree_document = parser.parse(f)
root = etree_document.getroot()
root.find(".//tr")
但这返回 None。我注意到如果我做 etree.tostring(root)
我取回了所有数据,但我所有的标签都以 html
开头(例如 <html:table>
)。但是root.find(".//html:tr")
抛出 KeyError。
有人可以让我回到正确的轨道上吗?
最佳答案
您可以使用以下命令关闭 namespace :
etree_document = html5lib.parse(t, treebuilder="lxml", namespaceHTMLElements=False)
关于python - BeautifulSoup 用户的 html5lib/lxml 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696265/