Python 将碎片输出到json文件
在完成了正式的tut之后,我决定尝试在同一个项目中构建我自己的spider。我在spiders目录中创建了parker_spider.py。其中包括:Python 将碎片输出到json文件,python,scrapy,Python,Scrapy,在完成了正式的tut之后,我决定尝试在同一个项目中构建我自己的spider。我在spiders目录中创建了parker_spider.py。其中包括: start_urls = [ "myurl" ] class Parker_Spider(scrapy.Spider): name = "parker" def start_requests(self): for i in range(self.max_id): yield
start_urls = [
"myurl"
]
class Parker_Spider(scrapy.Spider):
name = "parker"
def start_requests(self):
for i in range(self.max_id):
yield Request('myurl', method="post", headers= headers, body=payload, callback=self.parse_method)
def parse_method(self, response):
j = json.loads(response.body_as_unicode())
print(j['d'][0])
我可以看到spider运行时打印出正确的输出,因此我知道它在工作。现在我想将输出存储为JSON。当我跑步时:
$ scrapy crawl parker -o items.json
............
2016-05-31 16:53:55 [scrapy] INFO: Closing spider (finished)
2016-05-31 16:53:55 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 16112,
'downloader/request_count': 26,
'downloader/request_method_count/POST': 26,
'downloader/response_bytes': 12484,
'downloader/response_count': 26,
'downloader/response_status_count/200': 26,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2016, 5, 31, 20, 53, 55, 192000),
'log_count/DEBUG': 27,
'log_count/INFO': 7,
'response_received_count': 26,
'scheduler/dequeued': 26,
'scheduler/dequeued/memory': 26,
'scheduler/enqueued': 26,
'scheduler/enqueued/memory': 26,
'start_time': datetime.datetime(2016, 5, 31, 20, 53, 54, 31000)}
2016-05-31 16:53:55 [scrapy] INFO: Spider closed (finished)
items.json在项目目录中创建,但为空。我做错了什么
编辑:更改了spider代码,如下所示:
def parse_method(self, response):
j = json.loads(response.body_as_unicode())
ParkerItem.account=j['d'][0]
print(j['d'][0])
return ParkerItem.account
items.py:
class ParkerItem(scrapy.Item):
account = scrapy.Field()
现在,当我运行它时,我得到:
ERROR: Spider must return Request, BaseItem, dict or None, got 'unicode' in <POST myurl
错误:爬行器必须返回Request、BaseItem、dict或None,在中获得了“unicode”parse\u方法
需要返回scrapy.item.item
的实例或子类。实际上,它返回None
,Scrapy将其解释为无法从收到的响应中提取任何项。您的parse_方法
需要返回Scrapy.item.item
的实例或子类。实际上,它返回None
,Scrapy将其解释为无法从收到的响应中提取任何项目。谢谢!一个问题:为什么parse_方法函数中的项可用?我不进口,谢谢!一个问题:为什么parse_方法函数中的项可用?我不进口它。
def parse_method(self, response):
j = json.loads(response.body_as_unicode())
item = ParkerItem()
item['account'] = j['d'][0]
yield item