首页 > 解决方案 > 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)我得到 6,而不是 2,即使我已经检查len(table)并只得到 1(仅限第一个表)。那我该如何选择呢?

标签: pythonpython-3.xxpathscrapy

解决方案


您需要使用相对XPath:

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

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

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

推荐阅读