当我开始学习scrapy时,我遇到了动态构建Item属性的需求。我只是在抓取一个具有表格结构的网页,我想在抓取时形成项目和字段属性。我已经完成了这个示例抓取数据,而不必明确定义要抓取的每个字段,但无法充分利用它。
我是否应该编写一个项目管道来动态捕获信息。我也看过 Item loader 功能,但如果有人能详细解释一下,那将非常有帮助。
当我开始学习scrapy时,我遇到了动态构建Item属性的需求。我只是在抓取一个具有表格结构的网页,我想在抓取时形成项目和字段属性。我已经完成了这个示例抓取数据,而不必明确定义要抓取的每个字段,但无法充分利用它。
我是否应该编写一个项目管道来动态捕获信息。我也看过 Item loader 功能,但如果有人能详细解释一下,那将非常有帮助。
只需使用单个字段作为任意数据占位符。然后当你想把数据拿出来时,不要说for field in item
,你说for field in item['row']
。您不需要管道或加载器来完成此任务,但它们都被广泛使用是有充分理由的:它们值得学习。
蜘蛛:
from scrapy.item import Item, Field
from scrapy.spider import BaseSpider
class TableItem(Item):
row = Field()
class TestSider(BaseSpider):
name = "tabletest"
start_urls = ('http://scrapy.org?finger', 'http://example.com/toe')
def parse(self, response):
item = TableItem()
row = dict(
foo='bar',
baz=[123, 'test'],
)
row['url'] = response.url
if 'finger' in response.url:
row['digit'] = 'my finger'
row['appendage'] = 'hand'
else:
row['foot'] = 'might be my toe'
item['row'] = row
return item
输出:
stav@maia:/srv/stav/scrapie/oneoff$ scrapy crawl tabletest
2013-03-14 06:55:52-0600 [scrapy] INFO: Scrapy 0.17.0 started (bot: oneoff)
2013-03-14 06:55:52-0600 [scrapy] DEBUG: Overridden settings: {'NEWSPIDER_MODULE': 'oneoff.spiders', 'SPIDER_MODULES': ['oneoff.spiders'], 'USER_AGENT': 'Chromium OneOff 24.0.1312.56 Ubuntu 12.04 (24.0.1312.56-0ubuntu0.12.04.1)', 'BOT_NAME': 'oneoff'}
2013-03-14 06:55:53-0600 [scrapy] DEBUG: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2013-03-14 06:55:53-0600 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2013-03-14 06:55:53-0600 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2013-03-14 06:55:53-0600 [scrapy] DEBUG: Enabled item pipelines:
2013-03-14 06:55:53-0600 [tabletest] INFO: Spider opened
2013-03-14 06:55:53-0600 [tabletest] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2013-03-14 06:55:53-0600 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2013-03-14 06:55:53-0600 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2013-03-14 06:55:53-0600 [tabletest] DEBUG: Crawled (200) <GET http://scrapy.org?finger> (referer: None)
2013-03-14 06:55:53-0600 [tabletest] DEBUG: Scraped from <200 http://scrapy.org?finger>
{'row': {'appendage': 'hand',
'baz': [123, 'test'],
'digit': 'my finger',
'foo': 'bar',
'url': 'http://scrapy.org?finger'}}
2013-03-14 06:55:53-0600 [tabletest] DEBUG: Redirecting (302) to <GET http://www.iana.org/domains/example/> from <GET http://example.com/toe>
2013-03-14 06:55:53-0600 [tabletest] DEBUG: Redirecting (302) to <GET http://www.iana.org/domains/example> from <GET http://www.iana.org/domains/example/>
2013-03-14 06:55:53-0600 [tabletest] DEBUG: Crawled (200) <GET http://www.iana.org/domains/example> (referer: None)
2013-03-14 06:55:53-0600 [tabletest] DEBUG: Scraped from <200 http://www.iana.org/domains/example>
{'row': {'baz': [123, 'test'],
'foo': 'bar',
'foot': 'might be my toe',
'url': 'http://www.iana.org/domains/example'}}
2013-03-14 06:55:53-0600 [tabletest] INFO: Closing spider (finished)
2013-03-14 06:55:53-0600 [tabletest] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1066,
'downloader/request_count': 4,
'downloader/request_method_count/GET': 4,
'downloader/response_bytes': 3833,
'downloader/response_count': 4,
'downloader/response_status_count/200': 2,
'downloader/response_status_count/302': 2,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2013, 3, 14, 12, 55, 53, 848735),
'item_scraped_count': 2,
'log_count/DEBUG': 13,
'log_count/INFO': 4,
'response_received_count': 2,
'scheduler/dequeued': 4,
'scheduler/dequeued/memory': 4,
'scheduler/enqueued': 4,
'scheduler/enqueued/memory': 4,
'start_time': datetime.datetime(2013, 3, 14, 12, 55, 53, 99635)}
2013-03-14 06:55:53-0600 [tabletest] INFO: Spider closed (finished)
使用这个类:
class Arbitrary(Item):
def __setitem__(self, key, value):
self._values[key] = value
self.fields[key] = {}
在 Scrapy 1.0.3 中使用项目加载器时,自定义__setitem__
解决方案对我不起作用,因为项目加载器直接访问 fields 属性:
value = self.item.fields[field_name].get(key, default)
仅__setitem__
在项目级访问(如item['new field']
. 由于fields
只是一个 dict,我意识到我可以简单地创建一个 Item 子类,它使用 adefaultdict
来优雅地处理这些情况。
最后,只需要多出两行代码:
from collections import defaultdict
class FlexItem(scrapy.Item):
"""An Item that creates fields dynamically"""
fields = defaultdict(scrapy.Field)
在 Scrapy 1.0+ 中,如果您没有明确定义的模式,更好的方法可能是生成 Python dicts 而不是 Item 实例。检查例如http://scrapy.org/首页上的示例 - 没有定义项目。
我更期待使用项目加载器和管道处理数据的解释
假设:
fieldname = 'test'
fieldxpath = '//h1'
它(在最近的版本中)非常简单......
item = Item()
l = ItemLoader(item=item, response=response)
item.fields[fieldname] = Field()
l.add_xpath(fieldname, fieldxpath)
return l.load_item()