如何解决使用Scrapy从网站中提取所有下一页
但是,它只能刮取前4页,然后停止 这是代码:
def parse(self,response):
# follow links to property pages
for href in response.xpath('//div[@class="listings-item-bottom"]//a[@class="link link--minimal"]/@href').getall():
yield response.follow(href,self.parse_property)
# follow pagination links
old_offset = self.page_counter
old_offset = str(old_offset) + '0' if old_offset != 0 else str(old_offset)
try:
max_page = int(''.join(response.css('div.custom-pagination-select::text').re(r'\d+')))
except:
max_page = None
self.page_counter += 1
if self.page_counter < max_page:
new_offset = str(self.page_counter) + '0'
next_page_url = response._get_url().replace(f'offset={old_offset}',f'offset={new_offset}')
next_page = response.urljoin(next_page_url)
yield scrapy.Request(next_page,callback=self.parse)
有人对这里可能出什么问题有任何建议吗? 预先谢谢你!
解决方法
我认为您只需替换URL的偏移量即可到达下一页。
很显然,您可能需要对此进行概括,以便始终可以根据每次搜索的结果数来获取每个页面。
代码示例
def parse(self,response):
for href in response.xpath('//div[@class="listings-item-bottom"]//a[@class="link link--minimal"]/@href').getall():
yield response.follow(href,self.parse_property)
results_num = int(response.xpath('//div[@class="total-available-results"]/span/text()').get())
for i in range(10,results_num+10,10):
url = f'https://www.residentialpeople.com/za/property-for-sale/cape-town/?country=za&listing_type=residential&transaction_type=sale&longitude=18.49144&latitude=-33.98983&size_qualifier=square_feet&location_slug=cape-town&sort_by=closest_to_farthest&offset={i}&limit=10&active=1&status_available_only=0&_radius_expansion=0&_location=Cape%20Town,%20South%20Africa'
yield scrapy.Request(url=url,callback=self.parse,dont_filter=True)
解释
results_num
提供了属性的总数。我们使用for循环,其起始偏移量为10,在这种情况下为15720,请记住,我们需要在结束参数中加上+10,因为范围中的结束参数不包括results_num
。我们想要的步进参数是10。
我们为每个请求动态创建URL,在for循环中使用f字符串,为变量i
赋予我们上面想要的值。我们可以使用它为for循环的每次迭代所需的偏移量创建新的字符串URL。然后,我们可以通过调用parse函数来进行每次迭代的请求。请记住,因为URL的基数相同,所以scrapy将对其进行过滤,因此在Request
中,我们指定dont_filter=True
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。