简体   繁体   English

在Python中对Xpath查询使用变量

[英]Use a variable for an Xpath query in Python

[NB I'm quite new to Python & Xpath] [注意,我是Python和Xpath的新手]

I was wanting to perform an Xpath query and use a variable in the expression to cycle through all the elements using an index. 我想执行Xpath查询,并在表达式中使用变量来使用索引在所有元素之间循环。

For example, rather than having the specific position of [1] , [2] , etc, I'd like to be able to place a variable i in this expression: 例如,除了具有[1][2]等的特定位置,我希望能够在此表达式中放置一个变量i

for x in root.xpath('/movies/a_movie[i]/studio'):
    print "<studio>" + x.text + "</studio>"

I'm unsure whether it's even possible, but I guess it can't hurt to ask! 我不确定这是否有可能,但我想问问也不会有伤害!

To clarify, this is why I would like to do this: I'm trying to process all the elements of a_movie[1] , then at the end of the function, I want to process all the elements of a_movie[2] , and so on. 为了澄清,这就是为什么我要这样做:我正在尝试处理a_movie[1]所有元素,然后在函数的结尾,我想处理a_movie[2]所有元素,并且以此类推。

You want to loop over the /movies/a_movie tags instead, but only those that have a studio child: 您想改为遍历/movies/a_movie标记,但仅/movies/a_movie 具有 studio/movies/a_movie标记:

for a_movie in root.xpath('/movies/a_movie[studio]'):
    name = a_movie.find('name').text
    studio = a_movie.find('studio')
    print "<studio>" + studio.text + "</studio>"

If you wanted to just print out the child elements of the a_movie element as XML, I'd just loop over the element (looping over the child elements) and use ElementTree.tostring() on each: 如果您只想将a_movie元素的子元素以XML格式打印出来,我将遍历该元素(遍历所有子元素),并在每个元素上使用ElementTree.tostring()

for a_movie in root.xpath('/movies/a_movie'):
    for elem in a_movie:
        print ElementTree.tostring(elem),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM