gpt4 book ai didi

python - Scrapy - 动态创建字段的正确选择器

转载 作者:行者123 更新时间:2023-12-03 23:42:42 25 4
gpt4 key购买 nike

我正在使用网络抓取工具,但在获取正确的选择器时遇到了问题。这是我的代码:

# -*- coding: utf-8 -*-
import scrapy
import pandas as pd
from ..items import HomedepotpricespiderItem
from scrapy.http import Request


class HomedepotspiderSpider(scrapy.Spider):
name = 'homeDepotSpider'
allowed_domains = ['homedepot.com']






start_urls = ['https://www.homedepot.com/pep/304660691']#.format(omsID = omsID)
#for omsID in omsList]

def parse(self, response):

#call home depot function
for item in self.parseHomeDepot(response):
yield item

pass

def parseHomeDepot(self, response):

#get top level item
items = response.css('#zone-a-product')
for product in items:
item = HomedepotpricespiderItem()


#get the price
productPrice = product.xpath('//div[@class="price-format__main-price"]/span/text()').getall()

#get rid of all the stuff i dont need


item['productPrice'] = productPrice

yield item
因此,使用我当前的选择器,它看起来像是在抢夺这些商品的价格。
enter image description here
因为我的输出是:
'productPrice': ['$',
'2167',
'49',
'$',
'1798',
'00',
'$',
'2698',
'00',
'$',
'2099',
'99',
'$',
'2968',
'00',
'$',
'2294',
'99',
'$',
'2068',
'00',
'$',
'1649',
'99',
'$',
'2399',
'00',
'$',
'1649',
'99',
'$',
'1549',
'99',
'$',
'1799',
'99',
'$',
'3360',
'89',
'$',
'2899',
'95',
'$',
'3699',
'00',
'$',
'2719',
'96',
'$',
'1954',
'99',
'$',
'2699',
'00',
'$',
'2294',
'96',
'$',
'3149',
'00',
'$',
'3499',
'00',
'$',
'3749',
'00',
'$',
'4999',
'00',
'$',
'2799',
'99'],
什么时候正确的输出应该是:2099
此外,我认为我的选择器根本没有捕获商品的价格。

最佳答案

首先,您不需要使用 getall()如果您想接收 SINGLE 值(使用 get() 代替。您的表达式不起作用的另一个原因,因为您应该使用 相对 路径(对于您的 product 节点):

product.xpath('.//div[@class="price-format__main-price"]/span/text()').getall()
接下来,没有简单的方法可以使用单个 XPath 表达式获得格式正确的价格(实际上您可以使用 concat() 来实现),因为价格的整数部分和小数部分由 spans 分隔。 .最简单的方法(对我来说)是获取整个值,然后将其格式化为小数部分:
product_price = response.xpath('normalize-space(//div[@id="zone-a-product"]//div[@class="price"])').re_first(r'\$(.+)')
# product_price is 209999
更新
试试这个 XPath:
response.xpath('normalize-space(//div[@class="price"])').re_first(r'\$(.+)')

关于python - Scrapy - 动态创建字段的正确选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64828700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com