Scrapy: Define items dynamically

前端 未结 5 1374
别跟我提以往
别跟我提以往 2021-02-05 10:23

As I started to learn scrapy, i have come accross a requirement to dynamically build the Item attributes. I\'m just scraping a webpage which has a table structure and I wanted t

相关标签:
5条回答
  • 2021-02-05 10:36

    Use this class:

    class Arbitrary(Item):
        def __setitem__(self, key, value):
            self._values[key] = value
            self.fields[key] = {}
    
    0 讨论(0)
  • 2021-02-05 10:39

    In Scrapy 1.0+ the better way could be to yield Python dicts instead of Item instances if you don't have a well-defined schema. Check e.g. an example on http://scrapy.org/ front page - there is no Item defined.

    0 讨论(0)
  • 2021-02-05 10:50

    I was more xpecting about explanation in handling the data with item loaders and pipelines

    Assuming:

    fieldname = 'test'
    fieldxpath = '//h1'
    

    It's (in recent versions) very simple...

    item = Item()
    l = ItemLoader(item=item, response=response)
    
    item.fields[fieldname] = Field()
    l.add_xpath(fieldname, fieldxpath)
    
    return l.load_item()
    
    0 讨论(0)
  • 2021-02-05 10:57

    Just use a single Field as an arbitrary data placeholder. And then when you want to get the data out, instead of saying for field in item, you say for field in item['row']. You don't need pipelines or loaders to accomplish this task, but they are both used extensively for good reason: they are worth learning.

    spider:

    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
    

    outptut:

    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)
    
    0 讨论(0)
  • 2021-02-05 11:00

    The custom __setitem__ solution didn't work for me when using item loaders in Scrapy 1.0.3 because the item loader accesses the fields attribute directly:

    value = self.item.fields[field_name].get(key, default)
    

    The custom __setitem__ is only called for item-level accesses like item['new field']. Since fields is just a dict, I realized I could simply create an Item subclass that uses a defaultdict to gracefully handle these situations.

    In the end, just two extra lines of code:

    from collections import defaultdict
    
    
    class FlexItem(scrapy.Item):
        """An Item that creates fields dynamically"""
        fields = defaultdict(scrapy.Field)
    
    0 讨论(0)
提交回复
热议问题