ValueError:无法将字符串转换为浮点:(在python中)

ValueError:无法将字符串转换为浮点:(在python中),python,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) App

'这是我的代码'

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:无法将字符串转换为float:'

是的,因为它是'218,9'而不是'218.9'。您应该像这样更改错误行:

converted_price=float(价格[0:3]+'.+price[4])
价格检查

好的,如果我运行这个,那么我会得到一个错误值error:无法将字符串转换为float:'₹\XA05999.0'开头的符号是货币符号…现在,替换₹\使用空字符串“…或只使用下面的代码

    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 电子邮件已发送到请求的邮件

它可以工作。

对于长度未知的值,请尝试
float(price.replace(',',')
检查price列。您解析的值不正确意味着不是一个float值,因此不要转换为float first print as is is,并确定产生问题的行。
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()