python 中xpath之前怎么判断查找的节点是否存在
时间: 2024-03-26 13:40:29 浏览: 15
在Python中,我们可以使用XPath的`find`或`findall`方法来查找节点,如果节点不存在,这些方法会返回`None`或空列表。因此,我们可以根据返回值来判断节点是否存在。
例如,假设我们要查找一个XML文档中的`<title>`节点,我们可以使用以下代码:
```python
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
title = root.find('title')
if title is not None:
print(title.text)
else:
print('Title not found.')
```
如果`<title>`节点存在,上述代码将输出节点的文本内容;否则,将输出`Title not found.`。同样的,如果我们使用`findall`方法来查找节点,如果节点不存在,将返回一个空列表。
```python
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
titles = root.findall('title')
if len(titles) > 0:
for title in titles:
print(title.text)
else:
print('Titles not found.')
```
上述代码将输出所有`<title>`节点的文本内容,如果没有找到任何节点,则输出`Titles not found.`。