将项链接到scrapy中已解析的HREF

2024-06-16 11:46:08 发布

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

设置

用刮擦我刮房屋广告

根据ad-overview page,我获得一个列表,其中hrefs链接到各个广告。通过for循环,hrefs被发送到第二个解析器函数,以获得每个广告的外壳特征

def parse(self, response):
        # for href in list with hrefs
        for href in response.xpath(
                '//*[@id]/@href',
                ).extract()[1:-1]:
            yield scrapy.Request(response.urljoin(href),
                     callback=self.parse_ad)

def parse_ad(self, response):
# here follows code to obtain housing characteristics per ad

    yield {'char1': char1,
           'char2': char2,}

这个很好用


问题

除了hrefs,我还从广告概述页面获取了一个邮政编码列表

response.xpath('//*[@id]/div[1]/div/div[1]/div[1]/div[2]/meta').extract() 

最终我希望

    yield {'char1': char1,
           'char2': char2,
           'postal code': postal_code}

但我不知道该怎么做

  1. 使python同时选择href及其对应的postal_code
  2. postal_code移到parse_ad()下的yield函数

我该怎么办


Tags: selfdiv列表forparseresponsecodead
1条回答
网友
1楼 · 发布于 2024-06-16 11:46:08

要从一个回调方法“继续”到另一个回调方法,请使用^{}

def parse(self, response):
    for search_result in response.css(".room-tile.rowSearchResultRoom"):
        postal_code = search_result.css("meta[itemprop=postalCode]::attr(content)").extract_first()
        href = search_result.xpath("@href").extract_first()

        yield scrapy.Request(response.urljoin(href),
                             meta={'postal_code': postal_code},
                             callback=self.parse_ad)

def parse_ad(self, response):
    postal_code = response.meta['postal_code']

    # get char1 and char2..

    yield {'char1': char1,
           'char2': char2,
           'postal_code': postal_code}

相关问题 更多 >