首页 > 解决方案 > 如何将子函数与同一类中的父函数连接起来?

问题描述

class NewsSpider(CrawlSpider):
name = 'test12'
allowed_domains = ['news.daum.net']
start_urls = ['https://news.daum.net/breakingnews/digital']


rules = [
    Rule(LinkExtractor(allow=r'/breakingnews/digital\?page=\d$'),
         callback='parse_parent'),
]

def parse_parent(self, response):

    self.logger.info('Parent Response URL : %s' % response.url)

    for url in response.css('ul.list_news2.list_allnews > li > div'):

        article_url = url.css(
            'strong > a::attr(href)').extract_first().strip()

        yield scrapy.Request(article_url, self.parse_child, meta={'parent_url': response.url})

def parse_child(self, response):

    self.logger.info('-------------------------------------------')
    self.logger.info('Response From Parent URL : %s' %
                     response.meta['parent_url'])
    self.logger.info('Child Response URL : %s' % response.url)
    self.logger.info('Child Response Status : %s' % response.status)
    self.logger.info('-------------------------------------------')

这是我的代码

当我运行它时, parse_parent 只在类中运行,而 parse_child 不会作为结果出现。有没有错误的代码?

标签: pythonfunctionclass

解决方案


函数 parse_child 被称为异步,所以 self 不再是“self”。您可以尝试将 parse_child 转换为静态函数或类函数。


推荐阅读