皮屑:交出表格要求打印无?

2024-09-24 00:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个蜘蛛到废品的网站:

第一个urlwww.parenturl.com调用解析函数,从那里我提取了urlwww.childurl.com我有一个parse2函数的回调函数,它返回dict

问题1)我需要将dict值与从parse函数中的父url中提取的其他7个值一起存储在mysql数据库中?(响应url打印无)

def parse(self, response):
    for i in range(0,2):
        url = response.xpath('//*[@id="response"]').extract()
        response_url=yield SplashFormRequest(url,method='GET',callback=self.parse2)
        print response_url # prints None

def parse2(self, response):
    dict = {'url': response.url}
    return dict

Tags: 函数selfcomurlparse网站responsedef
2条回答

不能将yield调用等同于变量,因为它的作用类似于返回调用。在

试着把它取下来

def parse(self, response):
    self.results = []
    for i in range(0,2):
        url = response.xpath('//*[@id="response"]').extract()
        request = SplashFormRequest(url,method='GET',callback=self.parse2)
        yield request
    print self.results

def parse2(self, response):
    # print response here !
    dict = {'url': response.url}
    self.results.append(dict)

因为scrapy的asynchronous nature,所以在spider对象上存储第二次回调的结果并打印它不能保证正常工作。相反,您可以尝试passing additional data to callback functions,类似于:

def parse(self, response):
    for i in range(0, 2):
        item = ...  # extract some information
        url = ...  # construct URL
        yield SplashFormRequest(url, callback=self.parse2, meta={'item': item})

def parse2(self, response):
    item = response.meta['item']  # get data from previous parsing method
    item.update({'key': 'value'})  # add more information
    print item  # do something with the "complete" item
    return item

相关问题 更多 >