scrapy分页抓取网页(关于分页,最佳方法取决于所使用的分页类型)

优采云 发布时间: 2022-01-14 18:10

  scrapy分页抓取网页(关于分页,最佳方法取决于所使用的分页类型)

  关于分页,最好的方法实际上取决于所使用的分页类型。

  如果你:

  然后您可以一次安排所有页面:

  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)

  这种方法的巨大好处是速度 - 在这里您可以采用异步逻辑并同时抓取所有页面!

  或者。

  如果你:

  然后你必须同步安排页面 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 选择器选择正确的页面即可。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线