How to get all the deepest elements of a given type?

Viewed 47
<table>
   <tr>
      <td>cell 1</td>
   </tr>
   <tr>
      <td><b>cell 2</b></td>
   </tr>
   <tr>
      <td>
         <table>
            <tr>
               <td><span>cell 3</span></td>
            </tr>
         </table>
      </td>
   </tr>
</table>

Can I use XPath to get <td>cell 1</td>, <td><b>cell 2</b></td> and <td><span>cell 3</span></td>, but not the outer <td><table>... (because it has a nested td inside)?

Note the inner table here is just an example. I want the deepest td elements, meaning they cannot have another td as a descendant.

XPath 1.0 is preferred so I can use lxml.

This is a similar question, but here I know I want td elements.

2 Answers

//td will return every td in the document.

//td[not(.//td)] will return every td that does not contain (as one of its descendants) a td element.

Since a td must be a part of a table this XPath should be the fastest.

//td[not(descendant::table)]
Related