Scrapy不会选择第一个孩子的子元素,而是所有孩子的子元素

时间:2019-10-28 03:07:12

标签: python python-3.x xpath scrapy

有这个HTML:

<table class="myTable>
    <tbody>
        <tr>A1</tr>
        <tr>A2</tr>
    </tbody>
<table>

<table class="myTable>
    <tbody>
        <tr>A1</tr>
        <tr>A2</tr>
    </tbody>
<table>

<table class="myTable>
    <tbody>
        <tr>A1</tr>
        <tr>A2</tr>
    </tbody>
<table>

我只想提取A1A2一次。所以我有这个选择:

table = response.xpath('.//table[@class="myTable"]')[0]
row = table.xpath("//tr")

但是,当检查len(row)时,即使我检查了len(table)并只得到1(仅第一张表),我还是得到6,而不是2。那我该如何选择?

1 个答案:

答案 0 :(得分:1)

您需要使用相对 XPath:

row = table.xpath(".//tr")

或者您可以使用它来处理页面上的第一个表:

rows = response.xpath('(//table[@class="myTable"])[1]//tr')