You need to enable JavaScript to run this app. Python爬取的价格字符串如何转换为小数或货币类型存储至CSV
优惠活动
大模型
产品
解决方案
定价
更多

Python爬取的价格字符串如何转换为小数或货币类型存储至CSV

Python爬取字符串格式价格转Decimal/可存储数值类型的实现

核心处理思路

爬取拿到的价格字符串不是纯数字,通常混着货币符号、千分位逗号、多余空格这类杂质,直接强转类型肯定会报错。整个处理逻辑很简单:

  • 清洗杂质:把所有不属于数字、小数点、负号的字符全部剔除
  • 空值兼容:遇到XPath没匹配到内容返回的None值直接跳过,不做转换,避免流程崩溃
  • 选对类型:价格场景坚决不用float,因为浮点数有天生精度丢失问题(比如0.1+0.2算出来是0.30000000000000004),用Python内置的Decimal类型存储,不管是存CSV还是后续做价格计算都不会出精度问题。

具体实现步骤

1. 依赖导入

直接用Python标准库提供的Decimal模块,不需要额外安装第三方包:

from decimal import Decimal, InvalidOperation

2. 编写通用价格转换工具函数

把重复的转换逻辑封装成独立函数,避免Old_Price、Special_Price、Final_Price三个字段重复写冗余判断代码:

def str_to_price(price_str):
    # 没拿到内容直接返回None,不强行转换
    if not price_str:
        return None
    # 清洗:先去掉前后空格,再把除了数字、小数点、负号之外的字符全删掉
    cleaned = ''.join([
        char for char in price_str.strip()
        if char.isdigit() or char in ['.', '-']
    ])
    try:
        # 转成Decimal类型
        return Decimal(cleaned)
    except InvalidOperation:
        # 万一清洗完还是不符合格式,直接返回None,不因为单个商品的价格异常中断整个爬取
        return None

3. 改造原有爬虫parse逻辑

把原来直接存原字符串的价格字段,替换成调用工具函数转换后的结果:

def parse(self, response):
    count = 0
    for tv in response.xpath("//div[@class='products wrapper grid products-grid']/ol/li[@class='item product product-item']"):
        count +=1
        url = tv.xpath(".//div[@class='product-item-info']/div[@class='product details product-item-details']/strong/a/@href").get()
        name = tv.xpath(".//div[@class='product-item-info']/div[@class='product details product-item-details']/strong/a/text()").get()
        old_price = tv.xpath(".//div/span[@class='old-price']/span/span/span[@class='price']/text()").get()
        img = tv.xpath(".//div[@class='product-item-info']/a/span/span/img/@src").get()
        special_price = tv.xpath(".//div/span[@class='special-price']/span/span/span[@class='price']/text()").get()
        price = tv.xpath(".//div/div/span/span[@class='price-wrapper ']/span[@class='price']/text()").get()

        yield {
            'ID': count,
            'Name': name.strip() if name else name,
            'Description' : None,
            'Product_URL': url.strip() if url else url,
            # 价格字段调用统一转换函数处理
            'Old_Price': str_to_price(old_price),
            'Special_Price' : str_to_price(special_price),
            'Final_Price' : str_to_price(price),
            'Image_URL': img.strip() if img else img,
            'Category_ID' : 1
        }

存CSV的注意点

  • Decimal类型写入CSV的时候会原封不动保留数值精度,不会像float那样存完出现一堆无意义的小数位
  • 如果要统一保留两位小数,可以在转换完成后加一步格式统一:调用Decimal.quantize(Decimal('0.00')),比如把19.9自动格式化成19.90
  • 存的时候不用加货币符号,存纯Decimal数值就行,后续不管是算折扣、做价格区间筛选都能直接用,不用二次清洗数据

内容的提问来源于stack exchange,提问作者PHULUSO GOVERN RAMULIFHO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 20:45:04