lxml 相当于 BeautifulSoup “OR”句法?

发布于 2024-08-03 12:10:26 字数 283 浏览 3 评论 0原文

我正在将一些 html 解析代码从 BeautifulSoup 转换为 lxml。我试图找出以下 BeautifullSoup 语句的 lxml 等效语法:

soup.find('a', {'class': ['current zzt', 'zzt']})

基本上我想找到文档中具有“当前 zzt”或“zzt”类属性的所有“a”标签。 BeautifulSoup 允许传入一个列表、字典,甚至是正则表达式来执行匹配。

lxml 等效项是什么?

谢谢!

I'm converting some html parsing code from BeautifulSoup to lxml. I'm trying to figure out the lxml equivalent syntax for the following BeautifullSoup statement:

soup.find('a', {'class': ['current zzt', 'zzt']})

Basically I want to find all of the "a" tags in the document that have a class attribute of either "current zzt" or "zzt". BeautifulSoup allows one to pass in a list, dictionary, or even a regular express to perform the match.

What is the lxml equivalent?

Thanks!

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

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

发布评论

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

评论(1

浪荡不羁 2024-08-10 12:10:26

不,lxml 不提供您正在寻找的“首先查找或返回 None”方法。如果需要,只需使用 (select(soup) 或 [None])[0] 即可,或者编写一个函数来为您完成此操作。

#!/usr/bin/python
import lxml.html
import lxml.cssselect
soup = lxml.html.fromstring("""
        <html>
        <a href="foo" class="yyy zzz" />
        <a href="bar" class="yyy" />
        <a href="baz" class="zzz" />
        <a href="quux" class="zzz yyy" />
        <a href="warble" class="qqq" />
        <p class="yyy zzz">Hello</p>
        </html>""")

select = lxml.cssselect.CSSSelector("a.yyy.zzz, a.yyy")
print [lxml.html.tostring(s).strip() for s in select(soup)]
print (select(soup) or [None])[0]

好的,所以 soup.find('a') 确实会按照您的预期首先找到一个元素或 None 。问题是,它似乎不支持 CSSSelector 所需的丰富 XPath 语法。

No, lxml does not provide the "find first or return None" method you're looking for. Just use (select(soup) or [None])[0] if you need that, or write a function to do it for you.

#!/usr/bin/python
import lxml.html
import lxml.cssselect
soup = lxml.html.fromstring("""
        <html>
        <a href="foo" class="yyy zzz" />
        <a href="bar" class="yyy" />
        <a href="baz" class="zzz" />
        <a href="quux" class="zzz yyy" />
        <a href="warble" class="qqq" />
        <p class="yyy zzz">Hello</p>
        </html>""")

select = lxml.cssselect.CSSSelector("a.yyy.zzz, a.yyy")
print [lxml.html.tostring(s).strip() for s in select(soup)]
print (select(soup) or [None])[0]

Ok, so soup.find('a') would indeed find first a element or None as you expect. Trouble is, it doesn't appear to support the rich XPath syntax needed for CSSSelector.

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