HTML headers 上面的 XPath table?

XPath to HTML headers above a table?

我正在尝试在我的 python 脚本中获取 XPATH 字符串,它只会给我 headers <h2> 高于 table 的字符串。我是 XPath 的新手,但到目前为止我知道如果我做类似 //h2//text() 的事情,我会得到所有的 headers。但是,有什么方法可以创建 XPath,使其只需要 headers AB 而不是 C

import lxml.html as html
import lxml.etree as etree

x="""
<h2> A</h2>
<table>...</table>
<h2> B </h2>
<table>..</table>
<h2> C </h2>
"""
xt = etree.fromstring(x, parser=html.HTMLParser(recover=True,remove_comments=True))
print xt.xpath("//h2/text()")

这里是 selecting AB h2 元素的三个备选方案:

  1. 这个 XPath,

    //h2[position() = 1 or position() = 2]
    

    将 select 文档中的前两个 h2 元素。

  2. 这个 XPath,

    //h2[normalize-space()='A' or normalize-space()='B']
    

    将 select 那些 h2 元素,其 space 规范化字符串值为 "A""B".

  3. 这个 XPath,

    //h2[following-sibling::*[1][self::table]]
    

    将 select 那些 h2 紧随其后的兄弟是 table 元素的元素。