【问题标题】:Parse info from tables with Scrapy and XPath使用 Scrapy 和 XPath 从表中解析信息
【发布时间】:2018-11-22 20:04:27
【问题描述】:

我正在尝试使用 scrapy 和 xpath 从网站中提取属性:

response.xpath('//section[@id="attributes"]/div/table/tbody/tr/td/text()').extract()

属性嵌套如下:

<section id="attributes">
<h5>Attributes</h5>
    <div>
        <table>
            <tbody>
                <tr>
                    <td>Attribute 1</td>
                    <td>Value 1</td>
                </tr>           
                <tr>
                    <td>Attriburte 2</td>
                    <td>Value 2</td>
                </tr>

与此相关的有两个问题:

  1. 获取 td 元素的内容(XPath 命令将返回[])
  2. 检索到td 后,我需要以某种方式进行配对。例如:“属性 1”=“值 1”

我是 phyton 和 scrapy 的新手,非常感谢任何帮助。

【问题讨论】:

    标签: python xpath scrapy


    【解决方案1】:

    首先,您应该尝试从 XPath 中删除 tbody 标记,因为它通常不在页面源中。

    您可以按如下方式更新您的代码:

    cells = response.xpath('//section[@id="attributes"]/div/table//tr/td/text()').extract()
    att_values = [{first: second} for first, second in zip(cells[::2], cells[1::2])]
    

    您将获得属性值对列表:

    [{attr_1: value_1}, {attr_2: value_2}, {attr_3: value_3}, ...]
    

    att_values = {first: second for first, second in zip(cells[::2], cells[1::2])}
    

    获取字典

    {attr_1: value_1, attr_2: value_2, attr_3: value_3, ...}
    

    【讨论】:

    • 谢谢,效果很好。虽然我不明白生成字典的 att_values = 行。
    • @merlin ,假设我们有列表l = ['a', 1, 'b', 2, 'c', 3]...zip(l[::2], l[1::2]) 为我们生成元组('a', 1), ('b', 2), ('c', 3)[::2] 表示 给我们所有 even 列表中的元素[1::2] - 给我们所有 odd 元素。我们只是从每个元组的 2 个值中生成键值:{'a': 1, 'b': 2, 'c': 3}
    【解决方案2】:

    试试:

    for row in response.css('section#attributes table tr'):
        td1 = row.xpath('.//td[1]/text()').get()
        td2 = row.xpath('.//td[2]/text()').get()
        # your logic further
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多