使用 scrapy 在表格中查找正确的数据

Using scrapy to find the right data in tables

我想在一个有很多 table 的网站上获取文本。最终我想把它放到它处理相同布局的多个页面的地方。问题是 tables 的 xpath 可以改变。 xpath 在一页上可能是 table 3, row 4,在另一页上它可能是 table 2, row 5,以获取我需要的信息。我如何编写一个 xpath,如果它包含特定文本,它会选择 table,如果它包含特定文本,则选择该行,最后选择结束文本。

例如:

html 片段看起来像:

<table>
    <thead>
        <tr>
            <th colspan="2">
                <b>Table Blah</b>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th width="133" id="sub">
                <p align="right">
                    <b>Row Blah</b>
                </p>
            </th>
            <td>Get Me!</td>
        </tr>
    </tbody>
</table>

如果 <thead> 包含文本 Table Blah,而 <tbody> 中的 <tr> 包含文本 Row Blah 则抓取文本 Get Me!Row Blah<tr>

"Where if the <thead> contains the text Table Blah, and the <tr> in <tbody> contains the text Row Blah then grab the text Get Me! within Row Blah's <tr>"

将以上描述翻译成 XPath(为了便于阅读而格式化):

//table[contains(thead,'Table Blah')]
/tbody
/tr[contains(th,'Row Blah')]
/td

您可以编写 单个 XPath 表达式 并到达 Get me!:

//table[contains(thead/tr/th/b, 'Table Blah')]/tbody/tr[contains(th/p/b, 'Row Blah')]/td/text()

来自 shell 的演示(index.html 包含来自问题的相同数据):

$ scrapy shell index.html
In [1]: response.xpath("//table[contains(thead/tr/th/b, 'Table Blah')]/tbody/tr[contains(th/p/b, 'Row Blah')]/td/text())").extract()
Out[1]: [u'Get Me!']