我正在尝试使用 scrapy 从 url ' https://umanity.jp/en/racedata/race_6.php 开始跟踪去年的链接'。在此网址中,当前年份是 2018 年,并且有上一个按钮。当您单击该按钮时,它会转到 2017 年、2016 年……直到 2000 年。但是我编写的 scrapy 蜘蛛在 2017 年停止。我的代码:
import scrapy
class RaceSpider(scrapy.Spider):
name = 'test'
allowed_domains = ['umanity.jp']
start_urls = ['https://umanity.jp/en/racedata/race_6.php'] # start to scrape from this url
def parse(self, response):
previous_year_btn = response.xpath('//div[@class="newslist_year_select m_bottom5"]/*[1]')
if previous_year_btn.extract_first()[1] == 'a':
href = previous_year_btn.xpath('./@href').extract_first()
follow_link = response.urljoin(href)
yield scrapy.Request(follow_link, self.parse_years)
def parse_years(self, response):
print(response.url) # prints only year 2017
不明白为什么它停在 2017 年而不转到往年。有什么问题吗?
最佳答案
问题是 parse_years
函数不查找任何进一步的链接。
开关:
产生 scrapy.Request(follow_link, self.parse_years)
到
yield scrapy.Request(follow_link, self.parse)
并找到所有年份,因为 parse
函数不断查找链接。
如果您确实想要两个单独的函数(也许,parse_years
对数据执行某些操作,parse
查找下一个链接),这是可行的。
parse_years
只需要这个:
def parse_years(self, response):
print(response.url) # prints only year 2017
yield from self.parse(response)
关于python - Scrapy 遵循之前的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996404/