Python 如何使用lxml(如BeautifulSoup)搜索etree

Python 如何使用lxml(如BeautifulSoup)搜索etree,python,python-2.7,beautifulsoup,lxml,bs4,Python,Python 2.7,Beautifulsoup,Lxml,Bs4,假设我有以下xml: <?xml version="1.0" encoding="utf-8"?> <FeedType xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://foo.com/bar" xsi:schemaLocation="https://foo.com/bar https://foo.co

假设我有以下xml:

<?xml version="1.0" encoding="utf-8"?>
<FeedType xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://foo.com/bar" xsi:schemaLocation="https://foo.com/bar https://foo.com/bar/arr.xsd" value="Type">
    <ElementName value='Type'>
        <DataIWant>
            stuff
        </DataIWant>
        <DataIWant>
            other stuff
        </DataIWant>
    </ElementName>
</FeedType>
它将返回一个以
ElementName
作为根的树

如何在lxml中执行此操作

lxml
有一个可以使用的

但是,XML文档包含默认名称空间,因此搜索普通的
ElementName
标记将找不到它-您需要指定名称空间:

root.findall('foobar:ElementName', namespaces = {'foobar': 'https://foo.com/bar'})
如果不想指定名称空间,可以使用XPath查询忽略名称空间,只查找“本地名称”为
ElementName
的元素:

root.xpath("//*[local-name() = 'ElementName']")

lxml有一个findall方法。。。你试过用它了吗?使用
root.findall('ElementName')
返回无。@如果您尝试在那里使用答案,您会发现它对我的xml返回的
None
[]
不正确。示例代码:
xml=('stuffother stuff')
root=etree.fromstring(xml)
print(root.findall(“ElementName”)
是否可以忽略名称空间,或者像在BeautifuSoup中那样自动解析名称空间?@Dr,您可以使用XPath忽略名称空间-请查看我的更新答案是否可以执行类似
root.find_all('ElementName',{'href':'stuff'})
?与中一样,仅选择href属性为“stuff”的ElementNames?很抱歉要求这么高,但是lxml文档很难理解。是的,XPath支持这一点-您可以使用
root.XPath(“/*[local-name()='ElementName'和@href='stuff'])”
lxml文档可能不包括XPath教程,但您可以独立于lxml进行研究:)
root.xpath("//*[local-name() = 'ElementName']")