如何将BeautifulSoup抓取的标签内价格文本转换为整数进行数值运算
字符串类型价格无法进行算术运算的解决方法
报错原因
price_2通过text属性提取到的是包含数字、千分位空格、货币符号(₽、руб.)的字符串类型数据,无法直接与整数执行除法运算,必须先转换为数值类型。
解决步骤
- 第一步:清理价格字符串,过滤掉所有非数字的无关字符
- 第二步:将清理后的纯数字字符串转换为整数或浮点数类型
- 第三步:执行算术运算
代码示例
import re from bs4 import BeautifulSoup # 原有爬虫代码 soup = BeautifulSoup(src, 'lxml') price_2 = soup.find(class_='price-discount-value').find(class_='price').text.strip() x = 2 # 处理价格字符串:提取所有数字字符拼接为纯数字串 pure_price_str = ''.join(re.findall(r'\d+', price_2)) # 转换为整数类型,若价格存在小数可替换为float() price_num = int(pure_price_str) # 执行除法运算 price_3 = price_num / x print(price_3) # 输出结果为 1516.5
内容的提问来源于stack exchange,提问作者Vlad Vladov
相关产品推荐
相关产品推荐

