簡體   English   中英

ValueError:無法將字符串轉換為浮點數:(在 python 中)

[英]ValueError: could not convert string to float: (in 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:無法將字符串轉換為浮點數:'

是的,因為它是“218,9”而不是“218.9”。 您應該像這樣更改錯誤行:

converted_price = float(price[0:3] + '.' + price[4])
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字符串“”...或者只使用下面的代碼

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

go 通過上面的代碼你會知道我使用的變量並且可能會解決它...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()

價格檢查()

OUTPUT:JBL Tune 750BTNC 無線頭戴式無線主動降噪耳機,播放時間為 15 小時(黑色)5.999 email 已發送至要求的郵件..!
有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM