如何根据lxml中的子项选择父项?

ach*_*uns 5 html python xpath parsing 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>
Run Code Online (Sandbox Code Playgroud)

我想找到表但很难定位它(使用相同的代码10次).但我知道URL中的内容.我怎样才能获得父表?

Fre*_*Foo 5

如果tetree这个XML片段,那么您正在寻找的链接是

t.xpath('//a[@href = "http://exact url"]')[0]
Run Code Online (Sandbox Code Playgroud)

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

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