我正在尝试从页面抓取数据,并继续通过分页链接进行抓取。
我要抓取的页面是-> here
# -*- 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)
答案 0 :(得分:1)
它无效,因为url无效。如果您想继续使用scrapy.Request
,可以使用:
next_page_url = response.xpath('//link[@rel="next"]/@href').extract_first()
if next_page_url:
next_page_url = response.urljoin(next_page_url)
yield scrapy.Request(url=next_page_url, callback=self.parse)
一个简短的解决方案:
next_page_url = response.xpath('//link[@rel="next"]/@href').extract_first()
if next_page_url:
yield response.follow(next_page_url)
答案 1 :(得分:1)
要使代码正常工作,您需要使用response.follow()
或类似方法来修复断开的链接。请尝试以下方法。
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 response.follow(url=next_page_url, callback=self.parse)
您粘贴的代码严重缩进。我也已经解决了。