python - 如何选择网站的各种元素

标签 python web-scraping scrapy

我正在使用 scrapy 抓取一个网站,我想提取一些详细信息,例如产品的价格、产品描述、功能等。我想知道如何使用 css 选择器或 xpath 选择器选择每个元素并将它们存储为 xml 或 json 格式。

我编写了以下代码框架。请指导我应该从这里做什么。

enter image description here

# -*- coding: utf-8 -*-

import scrapy
import time


class QuotesSpider(scrapy.Spider):
    name = 'myquotes'
    
    start_urls = [
            'https://www.amazon.com/international-sales-offers/b/ref=gbps_ftr_m-9_2862_dlt_LD?node=15529609011&gb_f_deals1=dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL%252CEXPIRED%252CSOLDOUT%252CUPCOMING,sortOrder:BY_SCORE,MARKETING_ID:ship_export,enforcedCategories:15684181,dealTypes:LIGHTNING_DEAL&pf_rd_p=9b8adb89-8774-4860-8b6e-e7cefc1c2862&pf_rd_s=merchandised-search-9&pf_rd_t=101&pf_rd_i=15529609011&pf_rd_m=ATVPDKIKX0DER&pf_rd_r=AA0VVPMWMQM1MF4XQZKR&ie=UTF8'
                        
    ]

    def parse(self, response):
        
        
        all_div_quotes = response.css('a-section a-spacing-none tallCellView gridColumn2 singleCell')                    
        
        for quotes in all_div_quotes:
            
            
            title1 = all_div_quotes.css('.dealPriceText::text').extract()
            title2 = all_div_quotes.css('.a-declarative::text').extract()
            title3 = all_div_quotes.css('#shipSoldInfo::text').extract()        
        
            
        yield{
                'price' : title1,
                'details1' : title2,
                'details2' : title3                                  
                
            } 

我正在使用以下命令运行代码:

scrapy crawl myquotes -o myfile.json

将其保存在 json 文件中。此代码的问题在于它没有按预期返回标题、产品价格、产品描述。如果有人可以帮助我如何抓取亚马逊页面的产品名称、价格和描述,那将会有很大帮助。

最佳答案

检查和验证 CSS 选择器的更简单方法是使用 scrapy shell。 对于您的情况,我列出了您可以与代码一起使用的选择器:

名称:response.css("#productTitle::text").get()

价格:我的国家/地区没有价格,因此无法测试。

描述:response.css("#productDescription p::text").getall()

祝你好运。

关于python - 如何选择网站的各种元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864799/

相关文章:

python - 强制 mypy 对第三方包进行类型检查

python - Pygame RogueLike 窗口在运行函数时不启动

Python + Scrapy + MySQL UTF8编码错误

scrapy - 如何在运行时监控scrapy的状态

python scrapy 图像管道未下载(301 错误)

python - 比较 ID 的相同列行并将行减少为所需的输出

带有 BeautifulSoup 的 Python XMl 解析器。如何删除标签?

python - 使用 Scrapy shell 抓取 JSON 文件时终端窗口自动关闭

Excel VBA 宏抓取

python-2.7 - 使用 scrapy 递归地抓取 phpBB 论坛