[英]Python lxml. Use findall with a variable
An XML snippet looks like this: XML 片段如下所示:
<certificate name='first_item'>First text,</certificate>
<certificate name='second_item'>Second text,</certificate>
<certificate name='second_item'>Third text,</certificate
I can easily pick out an element using findall():我可以使用 findall() 轻松挑选出一个元素:
mystring = xmlroot.findall('certificate[@name="first_name"]').text
But I can't do that using a variable:但我不能使用变量来做到这一点:
item_option = 'first_item'
mystring = xmlroot.findall('certificate[@name=item_option]').text
full_search_string = 'certificate[@name="first_name"]'
mystring = xmlroot.findall(full_search_string).text
Both of these last options fail.最后这两个选项都失败了。 How do I insert a String variable into the findall() method?
如何将字符串变量插入 findall() 方法? If I don't want to hard code the filter based on name attribute, how can I do that?
如果我不想根据名称属性对过滤器进行硬编码,我该怎么做?
Try concatenating the variable to the string.尝试将变量连接到字符串。 Your variable is being passed as a string and therefore not interpreted.
您的变量作为字符串传递,因此不会被解释。
mystring = xmlroot.findall('certificate[@name="' + item_option + '"]')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.