Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select parent based on the child in lxml?

I have this code:

<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>

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?

like image 635
acheruns Avatar asked Feb 27 '12 19:02

acheruns


1 Answers

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]

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

t.xpath('//a[@href = "http://exact url"]/ancestor::table')[-1]
like image 140
Fred Foo Avatar answered Sep 27 '22 21:09

Fred Foo