Scrapy:从分页中抓取数据

时间:2018-09-09 03:34:08

标签: python xpath web-scraping scrapy

到目前为止,我已经从一页抓取了数据。我想继续到分页结束。

Click Here来查看页面

似乎有问题,因为href包含一个javascript元素。

<a href="javascript:void(0)" class="next" data-role="next" data-spm-anchor-id="a2700.galleryofferlist.pagination.8">Next</a>

我的代码

# -*- coding: utf-8 -*-
import scrapy


class AlibabaSpider(scrapy.Spider):
    name = 'alibaba'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/catalog/agricultural-growing-media_cid144?page=1']

def parse(self, response):
    for products in response.xpath('//div[contains(@class, "m-gallery-product-item-wrap")]'):
        item = {
            'product_name': products.xpath('.//h2/a/@title').extract_first(),
            'price': products.xpath('.//div[@class="price"]/b/text()').extract_first('').strip(),
            'min_order': products.xpath('.//div[@class="min-order"]/b/text()').extract_first(),
            'company_name': products.xpath('.//div[@class="stitle util-ellipsis"]/a/@title').extract_first(),
            'prod_detail_link': products.xpath('.//div[@class="item-img-inner"]/a/@href').extract_first(),
            'response_rate': products.xpath('.//i[@class="ui2-icon ui2-icon-skip"]/text()').extract_first('').strip(),
            #'image_url': products.xpath('.//div[@class=""]/').extract_first(),
         }
        yield item

    #Follow the paginatin link
    next_page_url = response.xpath('//link[@rel="next"]/@href').extract_first()
    if next_page_url:
        yield scrapy.Request(url=next_page_url, callback=self.parse)

问题

  • 如何解决分页问题?

您将如何提供帮助

  • 帮我修改代码,使我可以跟踪分页链接并将数据刮到最后。

2 个答案:

答案 0 :(得分:1)

要查找和解析类别中的所有页面,可以使用类似以下内容的东西:

myFragment =(myFragment)getFragmentManager().findFragmentById(R.id.external_display);
View view = myFragment.getView();
textureView = view.findViewById(R.id.camera_preview);
surfaceTexture = textureView.getSurfaceTexture();

答案 1 :(得分:1)

您可以使用类似的代码来获取下一页URL:

next_page_url = response.xpath('//div[@class="ui2-pagination-pages"]/span[@class="current"]/following-sibling::a[1][contains(@href, "?page=")]/@href').extract_first()

但是这将不起作用,因为分页块是由Javascript渲染的:-(

但是您可以使用某种技巧:

next_page_url = response.xpath('//link[@rel="next"]/@href').extract_first()
相关问题