lxml按名称查找元素,但在搜索中使用变量 [英] lxml find element by name, but use variable in search

查看:92
本文介绍了lxml按名称查找元素,但在搜索中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对lXML中的find函数有问题.但是我认为这是一个更常见的问题,如何告诉我要对照值而不是对象引用进行检查.

I have a problem with the find function in lXML. But i think this is more a generic question how to tell that i want to check against the value, not the object reference.

这是有效的代码:

step = xml_obj.find('.//step/name[text()="Design"]').getparent()

如果我尝试用对象替换字符串,则结果始终为None.

If i try to replace the string with an object, the result is always None.

stepn = 'Design'
step = xml_obj.find('.//step/name[text()=stepn]').getparent()

'NoneType' object has no attribute 'getparent'

推荐答案

stepn = 'Design'
step = xml_obj.find('.//step/name[text()={}]'.format(stepn)).getparent()

当您使用' '时,它是一个字符串,字符串中的任何元素都将被视为字符串,而不是变量.

when you use ' ', it's a string , any element in string will be treated as a string, not a variable.

使用format将变量添加到字符串

Use format to add variable to string

这篇关于lxml按名称查找元素,但在搜索中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆