我正在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请求。
我怎样才能归还我想要的东西
1条答案
按热度按时间yftpprvb1#
您需要获取
Author
的详细信息(除 last_article_date 之外的所有信息)和下一个yield
last_article_url
,并以cb_kwargs的形式传递您的Author
对象: