scrapy 如何使用response.follow()和回调函数来获取特定值?

dfddblmv  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(114)

我正在Scrapy中编写一个Spider,我尽可能地模块化了它(也许太多了)。
我有一个函数,它可以遍历作者的页面(如this one)并生成作者的信息:

def get_authors(self, response) -> Author:
        """Crawls through an author's page and yields author's information.
        """
        print('get_authors:')

        # Create a proto object.
        author = Author()
        author.id = '0' # CHANGE LIKE IN THE EXTRACTORS
        author.url = response.url
        author.name = str(self.get_author_name(response))
        author.topics = str(self.get_author_description(response))
        author.date_last = str(self.get_author_last_article_datetime(response)) # NOT WORKING
        ...

日期更容易从文章自己的页面提取,我已经有了一个函数。我的问题是该函数需要在不同的响应上运行。
我发现的对不同响应调用函数的唯一方法是执行response.follow(...)scrapy.Request(url, callback=func)。问题是这两个函数都没有返回我需要的结果。它们返回一个请求。
下面是有问题的部分:

def get_author_last_article_datetime(self, response):
        """Returns an author's latest article's date of publishing.

        Args:
            response:
                A response object of an author's page.

        Returns:
            A string containing the author's last article's pulishing date.

        Raises:
            Exception: An error occured while retrieving the author's last article url.
        """
        try:
            article_url = response.xpath('//div[@data-area="article_teaser>news-m-wide" and @data-pos="1:1"]//h2/a/@href').get()
            return str(response.follow(article_url, callback = self.get_article_datetime))
        except Exception:
            print("An error occured while retrieving the author's last article date.")
            last_date = 'N/A'
            return last_date

函数get_article_datetime() * 在给定文章页面时返回 * 一个时间对象。

当我运行get_authors而不是scrubbed date时,我得到一个GET请求。
我怎样才能归还我想要的东西

yftpprvb

yftpprvb1#

您需要获取Author的详细信息(除 last_article_date 之外的所有信息)和下一个yieldlast_article_url,并以cb_kwargs的形式传递您的Author对象:

def parse_author(self, response): 
    author = Author()
    author.id = '0' # CHANGE LIKE IN THE EXTRACTORS
    author.url = response.url
    author.name = str(self.get_author_name(response))
    author.topics = str(self.get_author_description(response))
    last_article_url = response.xpath('//div[@data-area="article_teaser>news-m-wide" and @data-pos="1:1"]//h2/a/@href').get()
    yield scrapy.Request(
        url=response.urljoin(last_article_url),
        cb_kwargs={
            'author': author,
        },
        callback=self.parse_last_article_date,
    )

   def parse_last_article_date(self, response, author):
      author.date_last = response.xpath('//some/xpath/here').get()
      yield author

相关问题