Question

I am getting this error:

ValueError: could not convert string to float: '$39.99'

Can someone please tell me whats wrong with my code?

import urllib.request

price = 99.99

while price > 4.74:

    page = urllib.request.urlopen("http://www.shoplavazza.com/products")
    text = page.read().decode("utf8")

    where = text.find('>$')

    start_of_price = where + 1

    end_of_price = start_of_price + 6

    price = float(text[start_of_price:end_of_price])

print("buy")
Was it helpful?

Solution

You have to do:

start_of_price = where + 2    #instead of 1

so that the price is 39.99 instead of $39.99 (which cannot be cast as a float).

OTHER TIPS

where = text.find('>$') # returns the location of >, not the location of $
start_of_price = where + 1 # this is now 1 + the location above, in other words $
end_of_price = start_of_price + 6
text[start_of_price:end_of_price] # Go from $ to 6 characters later.

As a note, you'll need to change that 6 to a 5. After all

text = 'hello>$39.99'
where = text.find('>$') # 5
start_of_price = where + 2 #starting at character 7, the '3'
end_of_price = start_of_price + 6 # there are only 5 chars after the $
text[start_of_price:end_of_price] # !OH NOS!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top