Skip to main content
 首页 » 编程设计

python之在函数之间传递类

2024年10月24日8linjiqin

我正在 Scrapy 中构建一个简单的(ish)解析器,当涉及到 scrapy 和 Python 时,我很幸运 :-) 在文件 item.py 中,我有一个 的定义我在下面的代码中分配给 item 的 thisItem()。一切都非常顺利,parse使用回调来获取 parse_dir_content...但后来我意识到我需要抓取一些额外的数据并创建了另一个函数 parse_other_content。如何将 item 中已有的内容放入 parse_other_content 中?

import scrapy 
from this-site.items import * 
import re 
import json 
 
class DmozSpider(scrapy.Spider): 
     name = "ABB" 
     allowed_domains = ["this-site.com.au"] 
     start_urls = [ 
        "https://www.this-site.com.au?page=1", 
        "https://www.this-site.com.au?page=2", 
    ] 
 
    def parse(self, response): 
        for href in response.xpath('//h3/a/@href'): 
            url = response.urljoin(href.extract()) 
            yield scrapy.Request(url, callback=self.parse_dir_contents) 
 
    def parse_dir_contents(self, response): 
        for sel in response.xpath('//h1[@itemprop="name"]'): 
            item = thisItem() 
            item['title'] = sel.xpath('text()').extract() 
            item['rate'] = response.xpath('//div[@class="rate"]/div/span/text()').extract() 
            so = re.search( r'\d+', response.url) 
            propID = so.group() 
            item['propid'] = propID 
            item['link'] = response.url 
            yield scrapy.Request("https://www.this-site.com.au/something?listing_id="+propID,callback=self.parse_other_content) 
            #yield item 
 
    def parse_other_content(self, reponse): 
            sel = json.loads(reponse.body) 
            item['rate_detail'] = sel["this"][0]["that"] 
            yield item 

我知道我在这里遗漏了一些简单的东西,但我似乎无法弄明白。

请您参考如下方法:

根据 scrapy 文档 ( http://doc.scrapy.org/en/1.0/topics/request-response.html#topics-request-response-ref-request-callback-arguments ):

In some cases you may be interested in passing arguments to those callback functions so you can receive the arguments later, in the second callback. You can use the Request.meta attribute for that.

在你的情况下我会做这样的事情:

def parse_dir_contents(self, response): 
    for sel in response.xpath('//h1[@itemprop="name"]'): 
        item = thisItem() 
        ... 
        request = scrapy.Request("https://www.this-site.com.au/something?listing_id="+propID,callback=self.parse_other_content) 
        request.meta['item'] = item 
        yield request 
 
def parse_other_content(self, response): 
    item = response.meta['item'] 
    # do something with the item 
    return item 

根据 Steve 的说法(见评论),您还可以将 meta 数据的字典作为关键字参数传递给 Request 构造函数,如下所示:

def parse_dir_contents(self, response): 
    for sel in response.xpath('//h1[@itemprop="name"]'): 
        item = thisItem() 
        ... 
        request = scrapy.Request("https://www.this-site.com.au/something?listing_id="+propID,callback=self.parse_other_content, meta={'item':item}) 
        yield request