gpt4 book ai didi

python - 如何在Python中忽略或传递xpath xml IndexError

转载 作者:行者123 更新时间:2023-12-01 05:56:06 25 4
gpt4 key购买 nike

如何强制 python 忽略 IndexError 而不使用 try except 我提取的每个值?

我的 XML 有多个需要提取的值。有些记录在 root[0] 处没有/值,因此我必须对要提取的每个节点手动使用 try & except IndexError:

这是我的代码:

try:
a = etree.XPath('/Data/a/b/nodeA/text()')(root)[0]
except IndexError:
a = ''
try:
b = etree.XPath('/Data/a/b/x/y/nodeB/text()')(root)[0]
except IndexError:
b = ''
try:
c = etree.XPath('/Data/a/b/d/nodeB/text()')(root)[0]
except IndexError:
c = ''

最佳答案

当我使用 xpath 查询时,我尝试使用循环而不是索引。这样,如果查询没有找到任何内容,则嵌套在循环中的代码永远不会运行,您也不会运行不必索引,因为循环值在每次迭代中都绑定(bind)到本地名称。允许举个例子。

for a, b, c in zip(
etree.XPath('/Data/a/b/nodeA/text()')
etree.XPath('/Data/a/b/x/y/nodeB/text()')
etree.XPath('/Data/a/b/d/nodeB/text()')):

print a, b, c

关于python - 如何在Python中忽略或传递xpath xml IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com