首页 > 解决方案 > ValueError:无法将字符串转换为浮点数:(在python中)

问题描述

“这是我的代码”

from bs4 import BeautifulSoup
import requests

URL = 'https://www.amazon.de/dp/B07KHKSZCJ?pf_rd_r=S1K975F9036B2X99PTNT&pf_rd_p=d1c766cf-ac59-4683-9885-c21368aa4f05'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36 OPR/68.0.3618.112'}



page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, "html.parser")

title = soup.find(id="productTitle").get_text()
price = soup.find(id="priceblock_ourprice").get_text()
converted_price = float(price[0:5])

if (converted_price > 100):
    print(title)
    print(price)


'它给了我这个错误可以帮助:ValueError:无法将字符串转换为浮点数:'

标签: python

解决方案


def price_check():
title = soup.find(id="productTitle").text
pg = soup.find(id="priceblock_ourprice").text
covt_pr=float(pg[0:9])
#covt_pr=float(pg.replace('₹\xa0' , '').replace(',', '.').replace('5.999.00', '5.999'))
print(title.strip())
print(covt_pr)
#if (covt_pr > 5.500):
    #send_mail()

价格检查()

好的,如果我运行它,那么我收到一个错误ValueError: could not convert string to float: '₹\xa05,999.0' 开头的符号是货币符号....现在,将₹\xa0替换为空string "" ...或者只使用下面的代码

    covt_pr=float(pg.replace('₹\xa0' , '').replace(',', '.').replace('5.999.00', '5.999'))

通过上面的代码你会知道我使用的变量并且可能会解决它...xd

def price_check():
title = soup.find(id="productTitle").text
pg = soup.find(id="priceblock_ourprice").text
covt_pr=float(pg.replace('₹\xa0' , '').replace(',', '.').replace('5.999.00', '5.999'))
print(title.strip())
print(covt_pr)
if (covt_pr > 5.500):
    send_mail()

价格检查()

输出:JBL Tune 750BTNC 头戴式无线主动降噪耳机,具有 15 小时播放时间(黑色)5.999 电子邮件已发送到请求的邮件..!
有用。


推荐阅读