Python Scrapy 抓取表格列和行

2024-10-01 11:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python上相对来说是个呆子,这是我第一次学习scrapy。我以前用perl做过数据挖掘,但这完全是另一回事!在

我试着刮一张表,抓取每一行的列。我的代码在下面。在

在项目.py在

from scrapy.item import Item, Field
class Cio100Item(Item):
   company = Field()
   person = Field()
   industry = Field()
   url = Field()

在刮伤.py(蜘蛛)

^{pr2}$

我在理解如何正确地表达xpath选择时遇到了一些困难。在

我认为这条线是问题所在:

      tables = sel.xpath('//table[@class="bgWhite listTable"]//h2')

当我按上述方式运行铲运机时,结果是在终端中得到这样的结果:

2014-01-13 22:13:29-0500 [scrape] DEBUG: Scraped from <200 http://www.cio.co.uk/cio100/2013/cio/>

{'company': [u"\nDomino's Pizza\n"],
 'industry': [u"\nDomino's Pizza\n"],
 'person': [u"\nDomino's Pizza\n"],
 'url': [u'/cio100/2013/dominos-pizza/']}

2014-01-13 22:13:29-0500 [scrape] DEBUG: Scraped from <200 http://www.cio.co.uk/cio100/2013/cio/>
{'company': [u'\nColin Rees\n'],
 'industry': [u'\nColin Rees\n'],
 'person': [u'\nColin Rees\n'],
 'url': [u'/cio100/2013/dominos-pizza/']}

理想情况下,我只想要一个街区,而不是两个街区,多米诺在公司的位置,科林在人的位置,而整个行业都在抢占,而这并不是它要做的。在

当我使用firebug检查表时,我看到第1列和第2列是h2(公司和个人),但第3列是h3?在

当我在末尾将tables行修改为h3时,如下所示

      tables = sel.xpath('//table[@class="bgWhite listTable"]//h3')

我明白了

2014-01-13 22:16:46-0500 [scrape] DEBUG: Scraped from <200 http://www.cio.co.uk/cio100/2013/cio/>
{'company': [u'\nRetail\n'],
 'industry': [u'\nRetail\n'],
 'person': [u'\nRetail\n'],
 'url': [u'/cio100/2013/dominos-pizza/']}

在这里它只生成1个块,并且它正确地捕获了行业和URL。但它没有得到公司的名字或人。在

任何帮助将不胜感激!在

谢谢!在


Tags: fromdebughttpurlfieldtablesxpathcompany
1条回答
网友
1楼 · 发布于 2024-10-01 11:32:34

就xpath而言,考虑执行以下操作:

$ scrapy shell http://www.cio.co.uk/cio100/2013/cio/
...
>>> for tr in sel.xpath('//table[@class="bgWhite listTable"]/tr'):
...     item = Cio100Item()
...     item['company'] = tr.xpath('td[2]//a/text()').extract()[0].strip()
...     item['person'] = tr.xpath('td[3]//a/text()').extract()[0].strip()
...     item['industry'] = tr.xpath('td[4]//a/text()').extract()[0].strip()
...     item['url'] = tr.xpath('td[4]//a/@href').extract()[0].strip()
...     print item
... 
{'company': u'LOCOG',
 'industry': u'Leisure and entertainment',
 'person': u'Gerry Pennell',
 'url': u'/cio100/2013/locog/'}
{'company': u'Laterooms.com',
 'industry': u'Leisure and entertainment',
 'person': u'Adam Gerrard',
 'url': u'/cio100/2013/lateroomscom/'}
{'company': u'Vodafone',
 'industry': u'Communications and IT services',
 'person': u'Albert Hitchcock',
 'url': u'/cio100/2013/vodafone/'}
...

除此之外,你最好一个一个地yield项,而不是将它们累加在一个列表中

相关问题 更多 >