如何在lxml中基于子项选择父项? [英] How to select parent based on the child in lxml?

查看:79
本文介绍了如何在lxml中基于子项选择父项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

<table cellspacing="1" cellpadding="1" border="0">
  <tbody>
   <tr>
    <td>Something else</td>
   </tr>
   <tr>
    <td valign="top">
      <a href="http://exact url">Something</a>
    </td>
    <td valign="top">Something else</td>
   </tr>
  </tbody>
</table>

我想找到表,但是很难定位它(使用相同的代码大约10次).但是我知道URL中有什么.我怎样才能得到父表?

I want to find the Table but is very hard to target it (the very same code is used like 10 times). But I know what is in the URL. How can I get then the parent table?

推荐答案

如果t是此XML代码段的etree,则您要查找的链接是

If t is the etree for this snippet of XML, then the link you're looking for is

t.xpath('//a[@href = "http://exact url"]')[0]

从那里,您可以使用ancestor轴到达table:

From there, you can get to the table using the ancestor axis:

t.xpath('//a[@href = "http://exact url"]/ancestor::table')[-1]

这篇关于如何在lxml中基于子项选择父项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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