python - 如何选择网站的各种元素
问题描述
我正在使用 scrapy 抓取一个网站,我想在其中提取一些细节,例如产品的价格、产品描述、功能等。我想知道如何使用 css 选择器或 xpath 选择器选择这些元素中的每一个,并将它们存储为 xml 或 json 格式。
我编写了以下代码骨架。请指导我从这里应该做什么。
# -*- 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()
祝你好运。
推荐阅读
- memory - 操作系统在硬盘的什么位置
- java - 不删除接受条件的文件(递归)
- reactjs - 我对 react-router-dom 有疑问,NoMatch 不接受 /foo/bar 之类的 URL
- r - 如何使填充的轮廓中的关键轴(z 图例)为空白,但保留绘图尺寸?
- phpunit - Codeception\Test\Test::run(?\Framework\TestResult $result = NULL) 必须兼容
- regex - 正则表达式 - 我如何循环执行结果
- r - 使用带有 `$` 运算符的 quasiquotation
- c - 如何使用IO复用技术提高服务器并发性能?
- c# - GetAssemblyName() 失败,而同一程序集上的 ReflectionOnlyLoadFrom() 成功?
- vbscript - 从映射的网络驱动器自动提升 VBS 不起作用