【发布时间】:2023-02-23 23:55:43
【问题描述】:
我是 Python 上的 scrapy 模块的新手,我对我的代码有疑问。
我要废弃的网站包含一些我想要废弃的数据。为此,我的蜘蛛在每个页面上爬行并检索一些数据。
我的问题是如何让它停止。当加载最后一页(第 75 页)时,我的蜘蛛程序将 url 更改为转到第 76 页,但网站并没有显示任何错误,而是一次又一次地显示第 75 页。在这里,当蜘蛛想要在第 76 页上爬行时,我通过自动要求停止来使其停止。但这并不准确,因为数据可能会发生变化,并且随着时间的推移,网站可能包含更多或更少的页面,不一定是 75 页。
你能帮我吗?我真的很感激 :)
这是我的代码:
import scrapy
from scrapy.exceptions import CloseSpider
class TowardsSustainabilitySpider(scrapy.Spider):
name = "towards_sustainability"
allowed_domains = ["towardssustainability.be"]
start_urls = ["https://towardssustainability.be/products?page=1"]
page_number = 1
def parse(self, response):
rows = response.xpath('//a[@class="Product-item"]')
for row in rows:
fund_name = row.xpath('./div/h2/text()').get()
yield {
'fund_name':fund_name
}
#go to the next page
self.page_number+=1
next_page = f'https://towardssustainability.be/products?page={self.page_number}'
if next_page == f'https://towardssustainability.be/products?page=76':
raise CloseSpider
yield response.follow(next_page, callback=self.parse)`
我尝试了一些事情:
- 第一页上有一个包含结果数量的框。考虑到每页包含 10 个结果,我所要做的就是将它除以 10,然后四舍五入得到最后一页的编号。没有成功,我不太清楚为什么..
- 只是尝试了 100 种不同的方法让它按时停止:当我的 csv 文件中出现元组时停止,尝试匹配上一页和当前页面的结果,... 没有什么能让它准时停止
【问题讨论】:
标签: python web-scraping scrapy web-crawler