我遇到了 Scrapy 的分页困难。 我通常使用以下代码成功
next_page = response.xpath("//div//div[4]//ul[1]//li[10]//a[1]//@href").extract_first()
if next_page is not None:
yield scrapy.Request(url = response.urljoin(next_page), callback=self.parse)
事实证明,在这次尝试中,我遇到了一个使用 5 个页面 block 的网站。请参见下图。
因此,在捕获前 5 页后,Scrapy 跳转到倒数第二页 (526)。
分页结构遵循以下逻辑:
https://www.example.com-1-data.html
并且它在数字上增加。 任何人都可以帮助我进行此分页的增量查询(基于示例地址)吗?
最佳答案
当谈到分页时,最佳方法实际上取决于所使用的分页类型。
如果你:
- 了解 url 页面格式
例如该 url 参数
page
表示您所在的页面 - 知道总页数
然后您可以一次安排所有页面:
def parse_listings_page1(self, response):
"""
here parse first page, schedule all other pages at once!
"""
# e.g. 'http://shop.com/products?page=1'
url = response.url
# e.g. 100
total_pages = int(response.css('.last-page').extract_first())
# schedule every page at once!
for page in range(2, total_pages + 1):
page_url = add_or_replace_parameter(url, 'page', page)
yield Request(page_url, self.parse_listings)
# don't forget to also parse listings on first page!
yield from self.parse_listings(response)
def parse_listings(self, response):
for url in response.css('.listing::attr(href)'):
yield Request(url, self.parse_product)
这种方法的巨大好处是速度 - 在这里您可以采用异步逻辑并同时抓取所有页面!
或者。
如果你:
- 除了页面上的下一页 url 之外不知道任何其他内容
然后你必须同步安排页面 1 到 1:
def parse(self, response):
for product in response.css('.product::attr(href)'):
yield Request(product, self.parse_product)
next_page = response.css('.next-page::attr(href)').extract_first()
if next_page:
yield Request(next_page, self.parse)
else:
print(f'last page reached: {response.url}')
在您的示例中,您使用的是第二种同步方法,您在这里的恐惧是没有根据的,您只需确保您的 xpath 选择器选择了正确的页面。
关于python - Scrapy/Python 中的增量分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54716360/