using xpath to select an element after another

Some alternatives to @Arup's answer:

tree.xpath("//p[b='Header 2']/following-sibling::table[1]")

select the first table sibling following the p containing the b header containing "Header 2"

tree.xpath("//b[.='Header 2']/following::table[1]")

select the first table in document order after the b containing "Header 2"

See XPath 1.0 specifications for details on the different axes:

  • the following axis contains all nodes in the same document as the context node that are after the context node in document order, excluding any descendants and excluding attribute nodes and namespace nodes

  • the following-sibling axis contains all the following siblings of the context node; if the context node is an attribute node or namespace node, the following-sibling axis is empty


You need to use the below XPATH 1.0 using the Axes preceding.

 //table[preceding::p[1]/b[.='Header 2']]

Tags:

Xpath

Lxml