lxml: get element with a particular child element?

大城市里の小女人 提交于 2019-12-08 06:17:08

问题


Working in lxml, I want to get the href attribute of all links with an img child that has title="Go to next page".

So in the following snippet:

<a class="noborder" href="StdResults.aspx">
<img src="arrowr.gif" title="Go to next page"></img>
</a>

I'd like to get StdResults.aspx back.

I've got this far:

next_link = doc.xpath("//a/img[@title='Go to next page']") 
print next_link[0].attrib['href']

But next_link is the img, not the a tag - how can I get the a tag?

Thanks.


回答1:


Just change a/img... to a[img...]: (the brackets sort of mean "such that")

import lxml.html as lh

content='''<a class="noborder" href="StdResults.aspx">
<img src="arrowr.gif" title="Go to next page"></img>
</a>'''

doc=lh.fromstring(content)
for elt in doc.xpath("//a[img[@title='Go to next page']]"):
    print(elt.attrib['href'])

# StdResults.aspx

Or, you could go even farther and use

"//a[img[@title='Go to next page']]/@href"

to retrieve the values of the href attributes.




回答2:


You can also select the parent node or arbitrary ancestors by using //a/img[@title='Go to next page']/parent::a or //a/img[@title='Go to next page']/ancestor::a respectively as XPath expressions.



来源:https://stackoverflow.com/questions/6892219/lxml-get-element-with-a-particular-child-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!