2024-10-02 10:21:10 发布
网友
我正在将一些html解析代码从beauthulsoup转换为lxml。我试图找出以下beauthoullsoup语句的lxml等价语法:
soup.find('a', {'class': ['current zzt', 'zzt']})
基本上,我想找到文档中所有class属性为“current zzt”或“zzt”的“a”标记。beauthulsoup允许用户传入一个列表、字典,甚至是一个常规的表达式来执行匹配。在
lxml的等价物是什么?在
谢谢!在
不,lxml没有提供您要寻找的“find first or return None”方法。如果需要的话,只需使用(select(soup) or [None])[0],或者编写一个函数来实现它。在
(select(soup) or [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')确实会像您所期望的那样首先找到一个元素或一个元素都没有。问题是,它似乎不支持CSSSelector所需的丰富XPath语法。在
soup.find('a')
不,lxml没有提供您要寻找的“find first or return None”方法。如果需要的话,只需使用
(select(soup) or [None])[0]
,或者编写一个函数来实现它。在好的,所以
soup.find('a')
确实会像您所期望的那样首先找到一个元素或一个元素都没有。问题是,它似乎不支持CSSSelector所需的丰富XPath语法。在相关问题 更多 >
编程相关推荐