python - BeautifulSoup 用户的 html5lib/lxml 示例?

标签 python beautifulsoup lxml html5lib

我正试图让自己摆脱 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/

相关文章:

Python 谷歌语音

python - VPS 服务器上的 Pygame.display.init() 错误 : "No available video device",

python - 与 Pandas 一起绘图时如何消除相对偏移?

python - 正则表达式按字面和被动方式匹配换行符

python-3.x - 使用 Robobrowser 登录亚马逊音乐

python - 浏览零售商网站上的每件产品

python - 如何将更新后的页面内容传递给另一个函数?

python - 从源安装 lxml 时为 "IOError: [Errno ftp error] 200 Type set to I"

python - 如何将 < 转换为 < in lxml,Python?

python - 如何在 lxml 中解析 XML 时不加载注释