我正在使用Scrapy(与SitemapSpider蜘蛛)构建www.apkmirror.com的刮板。到目前为止以下工作:如何填充作为字典的scrapy.Field
DEBUG = True
from scrapy.spiders import SitemapSpider
from apkmirror_scraper.items import ApkmirrorScraperItem
class ApkmirrorSitemapSpider(SitemapSpider):
name = 'apkmirror-spider'
sitemap_urls = ['http://www.apkmirror.com/sitemap_index.xml']
sitemap_rules = [(r'.*-android-apk-download/$', 'parse')]
if DEBUG:
custom_settings = {'CLOSESPIDER_PAGECOUNT': 20}
def parse(self, response):
item = ApkmirrorScraperItem()
item['url'] = response.url
item['title'] = response.xpath('//h1[@title]/text()').extract_first()
item['developer'] = response.xpath('//h3[@title]/a/text()').extract_first()
return item
其中ApkMirrorScraperItem
在items.py
定义如下:
class ApkmirrorScraperItem(scrapy.Item):
url = scrapy.Field()
title = scrapy.Field()
developer = scrapy.Field()
,如果我使用命令
scrapy crawl apkmirror-spider -o data.json
从项目目录运行它产生的JSON输出
是JSON字典数组,其密钥为url
,title
和developer
,以及t他将相应的字符串作为值。我想不过来修改这个,从而使developer
值本身就带有name
领域的字典,这样我可以这样来填充它:
item['developer']['name'] = response.xpath('//h3[@title]/a/text()').extract_first()
不过,如果我试试这个,我得到KeyError
小号,也如果我初始化developer
的Field
(这是dict
根据https://doc.scrapy.org/en/latest/topics/items.html#item-fields)为developer = scrapy.Field(name=None)
。我怎么去解决这个问题?