Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

python - ValueError: could not convert string to float: '2.283.00 - 5.331.00'

I'm creating a program 'Build A Python App That Tracks Amazon Prices!' but when I run the program it gives ValueError: could not convert string to float: '2.283.00 - 5.331.00'. I tried looking up for solutions but nothing worked. Here's my code:

import requests
from bs4 import BeautifulSoup
import smtplib

URL = "https://www.amazon.in/Nike-Trainer-Training-Shoes-8-924206-060/dp/B07FKG4SGQ/ref=sr_1_2? 
dchild=1&keywords=nike+shoes+for+men&qid=1609408052&sr=8-2"

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


def check_price():
    page = requests.get(URL, headers=headers)

    soup = BeautifulSoup(page.content, 'html.parser')
    title = soup.find(id="productTitle").get_text(strip=True)
    price = soup.find(id="priceblock_ourprice").get_text()
    converted_price = float(price.replace('?xa0' , '').replace(',', '.'))

    print(title)
    print(converted_price)

    if (converted_price > 4000):
        send_mail()


def send_mail():
    server = smtplib.SMTP('smtp.gmail.com', 587)    
    server.ehlo()
    server.starttls()
    server.ehlo()

    server.login('[email protected]', 'ezrdsmxfokoeihlb')

    subject = 'Price fell down!'
    body = 'check flipkart link https://www.amazon.in/Nike-Trainer-Training-Shoes-8-924206- 
    060/dp/B07FKG4SGQ/ref=sr_1_2?dchild=1&keywords=nike+shoes+for+men&qid=1609408052&sr=8-2'    

    msg = f"Subject: {subject}

{body}"

    server.sendmail(
      '[email protected]',
      '[email protected]',
      msg
   )

    print("Email has been sent!")

    server.quit()

check_price()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The obvious answer is that '2.283.00 - 5.331.00' is not something that can be converted to a float. It expects a format like '1.23'.

First of all it's a range, so you need to split that into two numbers on ' - '.

prices = soup.find(id="priceblock_ourprice").get_text().split(' - ')

Then replace the thousand separator ',' with '' on each price with:

price.replace('?xa0' , '').replace(',', '')

The better option might be to import locale and convert each of the prices (without the currency symbol) with locale.atof().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...