【问题标题】:Scrapy - Adding a table header (thead) value to Item LoaderScrapy - 将表头(thead)值添加到项目加载器
【发布时间】:2013-12-29 03:16:21
【问题描述】:

我有一个网页,其中包含多个我希望使用 Scrapy 抓取的表格:

<table>
   <thead>
      <tr>
         <th>
            <a>Heading1</a>
         </th>
      </tr>
      <tr>
         <th>Col1</th>
         <th>Col2</th>
         <th>Col3</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td><a href="#">Name1</a></td>
         <td>Description1</td>
         <td>Number1</td>
      </tr>
      <tr>
         <td><a href="#">Name2</a></td>
         <td>Description2</td>
         <td>Number2</td>
      </tr>

      ...

    </tbody>
</table>

一页上有很多类似上面的表格。

我正在使用一个项目加载器来存储循环遍历每一行的数据,抓取:

  • 姓名
  • 说明
  • 号码

Scrapy 蜘蛛如下:

class MySpider(BaseSpider):
   ...

   def parse(self, response):
      hxs = HtmlXPathSelector(response)
      tb = hxs.xpath('//table')

      for td in tb.xpath('.//tbody/tr'):
         il = WebsiteLoader(response=response, selector=td)

         il.add_xpath('name', 'td/a/text()')
         il.add_xpath('description', 'td[1]/text()')
         il.add_xpath('number', 'td[2]/text()')

         yield il.load_item()

这很好用,我可以让我的项目加载器在页面上同一个表的所有实例上填充每一行数据。

但是,我的问题是:

如何向我的项目加载器添加第 4 个字段,其中包含我抓取的每个表格的“标题”文本?

提前感谢您的帮助!


编辑

这是我目前可以抓取的数据示例:

Name1 | Description1 | Number1
Name2 | Description2 | Number2
...

# and so forth for the other table instances:

Name3 | Description3 | Number3
Name4 | Description4 | Number4
...

这就是我想要的:

Name1 | Description1 | Number1 | Heading1
Name2 | Description2 | Number2 | Heading1
...

# and so forth for the other table instances:

Name3 | Description3 | Number3 | Heading2
Name4 | Description4 | Number4 | Heading2
...

【问题讨论】:

  • 有人可以帮我解决这个问题吗?
  • 很难理解您要达到的目标,标题是每个表,您要求为您的项目提供第四个字段?您希望将所有项目中的标题作为第 4 个字段重复吗?如果是这样,您将如何在项目的单个字段中输入... 4 个标题?逗号分隔...
  • @Guy 感谢您的回复。每个表都没有自己单独的标题,我正在将数据抓取到数据库中。每一行我想将标题的第四个字段添加到它的记录中。所以是的,我想重复标题。
  • 请添加一个完整项目的外观示例,包括第 4 个字段
  • 那么,鉴于您共享的表格 html,HeadingX 将是什么? Heading1,Col1,Col2,Col3 在该表的每一行(项目)上重复?

标签: python scrapy


【解决方案1】:

我希望我理解正确,可能是这样的:

def parse(self, response):
   hxs = HtmlXPathSelector(response)
   for tb in hxs.xpath('//table'):

       heading = tb.xpath('.//thead/tr/th/a/text()').extract()[0]

       for td in tb.xpath('.//tbody/tr'):
          il = WebsiteLoader(response=response, selector=td)
          ...
          il.add_value('heading', heading)
          yield il.load_item()

【讨论】:

  • 现在我有了第一个标题,Heading1,已分配 - 谢谢!但是,下一个表的值不会更改为Heading2,而是使用相同的Heading1 值。这是我目前卡住的地方。
  • 非常感谢!我确实有一个索引超出范围错误,但我认为有一个幻像表正在被拾取,所以我将它更改为我想要的表类,它很有效!
  • 我猜你的一个/一些表缺少这种结构,如果没有看到真正的 html 页面很难分辨,尝试打印tb.xpath('.//thead/').extract() 并查看
  • 我编辑了我的评论 - 还有一张与其他桌子不同的桌子也被选中了 - 非常非常感谢你帮助我 :)
猜你喜欢
  • 2016-10-08
  • 1970-01-01
  • 2014-10-03
  • 2020-07-24
  • 1970-01-01
  • 2014-07-16
  • 2018-03-19
  • 2014-12-29
  • 2022-01-22
相关资源
最近更新 更多