Scrapy 在使用 yield 时不能 return item?
Scrapy can't return item when using yield?
我会尝试抽象我的代码,因为它有点大。
所以这个函数是用来解析论坛帖子的
def parse_thread_next_pages(self,response):
print("----- Scraping new NEXT THREAD PAGE ------")
for r in replies_body:
#Here I'm doing some parsing and adding to 'myitem'
if absolute_next_page_url=="javascript:;":
#We reached the last page, myitem contains all the information I need, I want to break and return it
break
else:
#This yield is used to call this function recursively for each pages
yield scrapy.Request(absolute_next_page_url, callback=self.parse_thread_next_pages,meta={'myitem': myitem})
return myitem
问题是,当我执行 scrapy crawl spider -t json -o result.json
时,它是空的。但是,如果我注释掉 yield
行,它就会起作用。但是很明显我没有得到预期的结果,因为这个解析函数没有被递归调用。
为什么会发生这种情况,在递归调用此函数并到达最后一页后,我如何 return 我的项目?
我认为您混淆了 python generators 的工作原理。
您的问题的一个替代方法是将最后的 return
也更改为 yield
。这不应该与你的功能冲突,Scrapy 从他们的回调中处理两件事,请求和项目。
我会尝试抽象我的代码,因为它有点大。
所以这个函数是用来解析论坛帖子的
def parse_thread_next_pages(self,response):
print("----- Scraping new NEXT THREAD PAGE ------")
for r in replies_body:
#Here I'm doing some parsing and adding to 'myitem'
if absolute_next_page_url=="javascript:;":
#We reached the last page, myitem contains all the information I need, I want to break and return it
break
else:
#This yield is used to call this function recursively for each pages
yield scrapy.Request(absolute_next_page_url, callback=self.parse_thread_next_pages,meta={'myitem': myitem})
return myitem
问题是,当我执行 scrapy crawl spider -t json -o result.json
时,它是空的。但是,如果我注释掉 yield
行,它就会起作用。但是很明显我没有得到预期的结果,因为这个解析函数没有被递归调用。
为什么会发生这种情况,在递归调用此函数并到达最后一页后,我如何 return 我的项目?
我认为您混淆了 python generators 的工作原理。
您的问题的一个替代方法是将最后的 return
也更改为 yield
。这不应该与你的功能冲突,Scrapy 从他们的回调中处理两件事,请求和项目。