【发布时间】: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在该表的每一行(项目)上重复?