Scrapy:直接从起始url解析一个变量的数据,并在从起始url跟随所有href之后解析其他变量的数据?

wz8daaqr  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(131)

我如何直接从起始url开始解析一个变量的数据,并在从起始url开始跟随所有href之后解析其他变量的数据呢?我想要刮取的网页有一个包含“类别”、“标题”、“内容”、“作者”和“日期”数据的文章列表。为了刮取数据,我跟踪了开始URL上的所有“href”,当从“href”打开/跟踪单个文章时,“category”数据并不总是可用的,所以它最终会丢失一些观测数据。现在,我试图刮只是“类别”的数据直接从开始的网址有“类别”的数据为所有的文章列表(没有丢失数据)。我应该如何解析“类别”数据?我应该如何处理解析和回调?“类别”数据在图中用红色圈出

class BtcNewsletterSpider(scrapy.Spider):
name = 'btc_spider'
allowed_domains = ['www.coindesk.com']
start_urls = ['https://www.coindesk.com/tag/bitcoin/1/']

def parse(self, response):
    for link in response.css('.card-title'):
        yield response.follow(link, callback=self.parse_newsletter)

def parse_newsletter(self, response):
    item = CoindeskItem()
    item['category'] = response.css('.kjyoaM::text').get()
    item['headline'] = response.css('.fPbJUO::text').get()
    item['content_summary'] = response.css('.jPQVef::text').get()
    item['authors'] = response.css('.dWocII a::text').getall()
    item['published_date'] = response.css(
        '.label-with-icon .fUOSEs::text').get()
    yield item

dzhpxtsq

dzhpxtsq1#

您可以使用cb_kwargs参数将数据从一个解析回调传递到另一个解析回调。要做到这一点,您需要获取指向全文的相应链接的类别值。这可以通过简单地遍历包含类别和链接的任何元素,并从所述元素中提取两者的信息来完成。
下面是一个基于您提供的代码的示例,它应该按照您描述的方式工作。

class BtcNewsletterSpider(scrapy.Spider):
    name = 'btc_spider'
    allowed_domains = ['www.coindesk.com']
    start_urls = ['https://www.coindesk.com/tag/bitcoin/1/']

    def parse(self, response):
        for card in response.xpath("//div[contains(@class,'articleTextSection')]"):
            item = CoindeskItem()
            item["category"] = card.xpath(".//a[@class='category']//text()").get()
            link = card.xpath(".//a[@class='card-title']/@href").get()
            yield response.follow(
                link,
                callback=self.parse_newsletter,
                cb_kwargs={"item": item}
            )

    def parse_newsletter(self, response, item):
        item['headline'] = response.css('.fPbJUO::text').get()
        item['content_summary'] = response.css('.jPQVef::text').get()
        item['authors'] = response.css('.dWocII a::text').getall()
        item['published_date'] = response.css(
            '.label-with-icon .fUOSEs::text').get()
        yield item

相关问题