【问题标题】:Scrapy - scrape of all of the item instead of 1 itemScrapy - 刮掉所有物品而不是一件物品
【发布时间】:2019-04-05 09:11:21
【问题描述】:

我需要刮掉所有的物品,但只有一件物品是刮掉的。 我的代码之前运行良好,但是当我将它转移到其他代码相同的项目时,我不知道为什么

我需要根据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】:

    您的缩进似乎有问题。将屈服请求移至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)
    

    【讨论】:

    • 天哪!我刚刚忽略了我的代码并忘记了缩进,现在它工作正常感谢@vezunchik
    • 如果您能接受答案,那就太好了,谢谢!
    • 感谢 Vezunchik,这是一个额外的帮助
    猜你喜欢
    • 2021-10-18
    • 2016-01-14
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2021-03-02
    • 2017-12-25
    相关资源
    最近更新 更多