如何像在 Xpath 中一样在 ElementTree 中进行查询?

发布于 2024-12-27 13:51:26 字数 545 浏览 2 评论 0原文

这是我可能在 PHP 中执行的示例查询:

foreach(steps as step)
{
  areT_eles = xpath->query(t_eleQuery, step)
}

现在在 python 中:

for step in index steps:
  areT_eles = ?!?!?!?!!??!?!!??!!

我尝试了这个:

for step in index steps:
  areT_eles = xpath.query(t_eleQuery, step)

它不起作用。不过,我只从 xml.etree.ElementTree 导入了 Elementtree。

我在 elementtreexpath 上找到的最官方的页面实际上没有任何文档或示例......而且我们都知道 Python 官方的教程有多么糟糕是。所以,我也在寻找好的资源。

This is a sample query I might do in PHP:

foreach(steps as step)
{
  areT_eles = xpath->query(t_eleQuery, step)
}

Now in python:

for step in index steps:
  areT_eles = ?!?!?!?!!??!?!!??!!

I tried this:

for step in index steps:
  areT_eles = xpath.query(t_eleQuery, step)

It didn't work. I've only imported Elementtree from xml.etree.ElementTree, though.

The most official page I was able to find on xpath in elementtree actually didn't have any documentation or examples.... And we all know how horribly bad Python official's tutorials are. So, I'm also looking for a good resource.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫离伤花 2025-01-03 13:51:26

如果您安装了 LXML(ElementTree 的高性能、全功能版本),您可以按如下方式使用 XPath:

>>> from lxml import etree
>>> xml = """<ham><spam>Hello!</spam> <spam>Goodbye!</spam></ham>"""
>>> tree.xpath("//spam/text()")
['Hello!', 'Goodbye!']

我可以推荐 LXML 来满足您所有的 Python XML 需求;它快速且Pythonic。

If you have LXML, the high-performance, full-featured version of ElementTree, installed you can use XPath as follows:

>>> from lxml import etree
>>> xml = """<ham><spam>Hello!</spam> <spam>Goodbye!</spam></ham>"""
>>> tree.xpath("//spam/text()")
['Hello!', 'Goodbye!']

I can recommend LXML for all your Python XML needs; it's fast and Pythonic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文