Python 将参数传递给回调函数
我在主解析方法中删除了一整张表,并从该表中提取了几个字段。其中一个字段是一个url,我想对它进行探索,以获得一组全新的字段。如何将已创建的ITEM对象传递给回调函数,以便最终的ITEM保留所有字段 正如上面的代码所示,我能够保存url内的字段(目前的代码)或仅保存表中的字段(只需编写Python 将参数传递给回调函数,python,callback,arguments,scrapy,Python,Callback,Arguments,Scrapy,我在主解析方法中删除了一整张表,并从该表中提取了几个字段。其中一个字段是一个url,我想对它进行探索,以获得一组全新的字段。如何将已创建的ITEM对象传递给回调函数,以便最终的ITEM保留所有字段 正如上面的代码所示,我能够保存url内的字段(目前的代码)或仅保存表中的字段(只需编写yield item) 但我不能把所有的场都放在一起,只产生一个物体 我已经试过了,但是很明显,它不起作用 def parse(self, response): for sel in response.xpa
yield item
)
但我不能把所有的场都放在一起,只产生一个物体
我已经试过了,但是很明显,它不起作用
def parse(self, response):
for sel in response.xpath('//tbody/tr'):
item = HeroItem()
item['hclass'] = response.request.url.split("/")[8].split('-')[-1]
item['server'] = response.request.url.split('/')[2].split('.')[0]
item['hardcore'] = len(response.request.url.split("/")[8].split('-')) == 3
item['seasonal'] = response.request.url.split("/")[6] == 'season'
item['rank'] = sel.xpath('td[@class="cell-Rank"]/text()').extract()[0].strip()
item['battle_tag'] = sel.xpath('td[@class="cell-BattleTag"]//a/text()').extract()[1].strip()
item['grift'] = sel.xpath('td[@class="cell-RiftLevel"]/text()').extract()[0].strip()
item['time'] = sel.xpath('td[@class="cell-RiftTime"]/text()').extract()[0].strip()
item['date'] = sel.xpath('td[@class="cell-RiftTime"]/text()').extract()[0].strip()
url = 'https://' + item['server'] + '.battle.net/' + sel.xpath('td[@class="cell-BattleTag"]//a/@href').extract()[0].strip()
yield Request(url, callback=self.parse_profile)
def parse_profile(self, response):
sel = Selector(response)
item = HeroItem()
item['weapon'] = sel.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4]
return item
这就是您使用
meta
关键字的目的
yield Request(url, callback=self.parse_profile(item))
def parse_profile(self, response, item):
sel = Selector(response)
item['weapon'] = sel.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4]
return item
另外请注意,执行
sel=Selector(response)
是一种资源浪费,与您之前所做的不同,因此我对其进行了更改。它在响应中自动映射为response.selector
,它还有response.xpath
的快捷方式。我对Tkinter的额外参数传递有类似的问题,并发现此解决方案可行(此处:),转化为您的问题:
def parse(self, response):
for sel in response.xpath('//tbody/tr'):
item = HeroItem()
# Item assignment here
url = 'https://' + item['server'] + '.battle.net/' + sel.xpath('td[@class="cell-BattleTag"]//a/@href').extract()[0].strip()
yield Request(url, callback=self.parse_profile, meta={'hero_item': item})
def parse_profile(self, response):
item = response.meta.get('hero_item')
item['weapon'] = response.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4]
yield item
下面是将参数传递给回调函数的更好方法:
def parse(self, response):
item = HeroItem()
[...]
def handler(self = self, response = response, item = item):
""" passing as default argument values """
return self.parse_profile(response, item)
yield Request(url, callback=handler)
资料来源:@peduDev
尝试了您的方法,但由于意外的关键字而失败
def parse(self, response):
request = scrapy.Request('http://www.example.com/index.html',
callback=self.parse_page2,
cb_kwargs=dict(main_url=response.url))
request.cb_kwargs['foo'] = 'bar' # add more arguments for the callback
yield request
def parse_page2(self, response, main_url, foo):
yield dict(
main_url=main_url,
other_url=response.url,
foo=foo,
)
除了对旧版本的修改之外,知道是什么导致了意外的关键字参数吗
是的。我验证了我自己的建议,升级后,一切正常
sudo pip install——升级scrapy试着看看decorators,例如,url返回item
中不存在的字段,您想将这些字段添加到item
并返回它吗?您是否成功地实现了这一点?这是一个危险的建议。他正在遍历response.xpath('//tbody/tr')
中找到的所有“项”。由于请求不会在回调(ever)中提供项作为参数,因此处理程序方法将始终使用项作为默认项。不幸的是,该项在进行回调调用时是什么,而不是在生成请求时是什么。您收集的数据将不可靠且不一致。@否,通过在函数头(self=self…)中分配变量,它在执行函数定义时保存变量值。只要handler
的定义在循环中,parse\u profile
就会得到被迭代的每个项的值。这是一个非常优雅的解决方案。@AlanHoover我的印象是,由于请求的回调可以在以后发生,函数本身被重新定义,并且在执行回调时调用重新定义的函数。我记得自己也遇到过这种情况,我非常确定我没有对任何参数进行任何后期绑定。我要做一些测试!
scrapy_req = scrapy.Request(url=url,
callback=self.parseDetailPage,
cb_kwargs=dict(participant_id=nParticipantId))
def parseDetailPage(self, response, participant_id ):
.. Some code here..
yield MyParseResult (
.. some code here ..
participant_id = participant_id
)
Error reported
, cb_kwargs=dict(participant_id=nParticipantId)
TypeError: _init_() got an unexpected keyword argument 'cb_kwargs'