Scrapy - 刮掉所有物品而不是1件物品

问题描述 投票:0回答:1

我需要刮掉所有物品,但只有一件物品刮掉。我的代码工作正常,但当我将它转移到其他项目,这是相同的代码,我不知道为什么

我需要根据start_url中的页面大小获取所有项目

这是我的工作代码

class HmSalesitemSpider(scrapy.Spider):
    name = 'HM_salesitem'
    allowed_domains = ['www2.hm.com']
    start_urls = ['https://www2.hm.com/en_us/sale/shopbyproductladies/view- 
all.html?sort=stock&image-size=small&image=stillLife&offset=0&page- 
size=3002']

def parse(self, response):  
    for product_item in response.css('li.product-item'):
        url = "https://www2.hm.com/" + product_item.css('a::attr(href)').extract_first() 
    yield scrapy.Request(url=url, callback=self.parse_subpage)

def parse_subpage(self, response):
    item = {
    'title': response.xpath("normalize-space(.//h1[contains(@class, 'primary') and contains(@class, 'product-item-headline')]/text())").extract_first(),
    'sale-price': response.xpath("normalize-space(.//span[@class='price-value']/text())").extract_first(), 
    'regular-price': response.xpath('//script[contains(text(), "whitePrice")]/text()').re_first("'whitePrice'\s?:\s?'([^']+)'"),
    'photo-url': response.css('div.product-detail-main-image-container img::attr(src)').extract_first(),
    'description': response.css('p.pdp-description-text::text').extract_first()

    }   
    yield item

请帮忙。谢谢

python css xpath web-scraping scrapy
1个回答
0
投票

看来你有缩进问题。将屈服请求移至for循环:

def parse(self, response):  
    for product_item in response.css('li.product-item'):
        url = "https://www2.hm.com/" + product_item.css('a::attr(href)').get() 
        yield scrapy.Request(url=url, callback=self.parse_subpage)

或者这是一个有点清除的版本:

def parse(self, response):  
    for link in response.css('li.product-item a::attr(href)').extract():
        yield response.follow(link, self.parse_subpage)
© www.soinside.com 2019 - 2024. All rights reserved.