浏览简陋的教程,并开始使用项目加载器来收集数据。我使用的数据包括从通过JSON加载的预定义字典和由爬行器跟随的产品页面中读取数据。

我遇到的问题是,字典有时没有可用键(如'salePrice'),这会导致爬网中出现KeyError并完全停止执行。我正在尝试看看在items.py中是否有一种干净的方法来处理这个字段的KeyErrors,其中为每个字段指定了input_processors和output_processors。

如果有任何建议或例子,我将不胜感激!

import json
import re
import time

import scrapy
from scrapy.loader import ItemLoader
from tutorial.items import Product

class SephoraSpider(scrapy.Spider):
    
    name = 'sephora-shelf'
    start_urls = [
        'https://www.sephora.com/shop/moisturizing-cream-oils-mists/?currentPage=1'
    ]
    next_page_number = 1
    base_url = 'https://www.sephora.com'


    def parse(self, response):
        json_xpath = '//script[@type="text/json" and @id="linkSPA"]/text()'
        product_container = json.loads(response.xpath(json_xpath).extract()[0])
        product_container = product_container['NthCategory']['props']['products']
        start_time = round(time.time())
        print("starting loop")
        for _product in product_container:
            product = Product()
            loader = ItemLoader(item=Product(), response=response)
            loader.add_value('list_price', _product['currentSku']['listPrice'])
            loader.add_value('sale_price', _product['currentSku']['salePrice'])
            loader.add_value('sku_id', _product['currentSku']['skuId'])

            loader.add_value('product_key', _product['productId'])
            loader.add_value('product_name', _product['displayName'])
            loader.add_value('brand_name', _product['brandName'])
            loader.add_value('product_id', _product['productId'])
            
            _product_url = self.base_url + _product['targetUrl']
            loader.add_value('product_url', _product_url)
            loader.add_value('status', None)
            print("finished loading product")
            
            # TODO: add a check to see if it was on the previous run's data
            #       to determine if it is product status: added / deleted.
            #       Only collect product data if the product is newly added.
            yield response.follow(_product_url, callback=self.parse_product,
                                  meta={'item':loader.load_item()})

        next_page_xpath = '//button[@type="button" and @aria-label="Next"]'
        next_page_button = response.xpath(next_page_xpath)
        print(f'next_page_button: {next_page_button}')
        
        if next_page_button:
            print("Inside next_page_button")
            SephoraSpider.next_page_number += 1
            next_page = re.sub('\?currentPage=[0-9]*',
                               '?currentPage=' + 
                               str(SephoraSpider.next_page_number),
                               response.request.url)
            print(f"Next Page: {next_page}")
            yield response.follow(next_page, callback=self.parse)

    
    def parse_product(self, response):
        loader = ItemLoader(item=response.meta['item'], 
                            response=response)
        loader.add_xpath('item_id', '//div[@data-at="sku_size"]')
        time.sleep(3)
        yield loader.load_item()

转载请注明出处:http://www.yutianjidian.com/article/20230526/2371329.html

随机推荐

  1. 在scrapy中,有没有从div中获取完整文本的方法?

    我正在与scrapy工作,以便从网页的某些部分爬行的内容。我需要的文本被刮完全一样在网页上显示。该网页的结构类似于此。div class = uselessInfo.../div div class = usefulInfo ...

  2. 如何使用Scrapy在类中获取HTML代码

    有没有可能在div类messageContent中获得完整的HTML代码,包括HTML代码本身?This是URL。但是我不能得到整个消息和它的格式,这是可能的吗?我试过的是:item.css(div.messageContent block...

  3. 在Scrapy中一次生成多个项目

    如何同时生成多个项目?我正在抓取一个URLS列表,其中每个URLs都有大约10-20个嵌套的URLs。我从每个嵌套的URL中抓取需要生成的10项信息。有没有办法同时生产10件商品?也许是通过一个列表,或者我附加每一项,然后在最后生成所有项的...

  4. 如何在此网页中使用scrapy刮掉所有加粗的部分标题?

    所以我想把这个网页上所有粗体的部分标题都去掉。简称,解释,法案的管理……但到目前为止,我只能在第一部分的前两个部分这样做。import scrapy class ActScraper1Spider(scrapy.Spider): ...

  5. 如何在Spyder或VScode中使用Scrapy

    我希望你们都很好,做得很好。我想在Spyder中使用Scrapy,而不是通过终端/shell使用它。我是一个windows用户,Scrapy版本1.8.0,pyhton 3.7.3,我正面临着BeautifulSoup的问题。例如,我试图从...

  6. 如何在amazon爬行器中使用scrapy的Itemloader,以便从输出中删除所有换行符或额外的空格

    我正在尝试使用scrapy抓取amazon,除了作者字段之外,一切都很好,我得到的输出如下,{author: [Somasundaram Chenrayan, B. Latha B. ???, ...

  7. 在scrapy中使用ItemLoader将缺省值设置为None的KeyError处理

    浏览简陋的教程,并开始使用项目加载器来收集数据。我使用的数据包括从通过JSON加载的预定义字典和由爬行器跟随的产品页面中读取数据。我遇到的问题是,字典有时没有可用键(如salePrice),这会导致爬网中出现KeyError并完全停止执行。...

  8. 如何在Scrapy中使用xpath抓取没有类或属性的标记?

    我正在尝试抓取一个html文件,但是标签没有任何class或id。有没有办法在不使用常规的//*class=blah/‘格式的情况下获得xpath?

  9. 在python (jupyter notebook)中使用scrapy拉取特定数据?

    我正在尝试使用jupyter notebook运行一个爬虫来获取特定的数据-在这种情况下,结果应该从链接的下拉列表中获取21个服务“。我有以下代码:import scrapy from scrapy.crawler import Crawl...

  10. 如何在scrapy中使用CrawlSpider处理http错误代码

    我正在尝试使用scrapy来测试一些网站及其子网站的http返回码,分别检测400和500范围内的错误。然而,另外,我也希望看到并处理300范围内的代码。我已经尝试了几天并查看了文档,但是我被卡住了,没有找到解决方案。谢谢你的帮助!跟随您将...