0

I'm trying to learn python. I am using 3.1.2 and the o'reilly book is using 3.0.1 here is my code:

import urllib.request

price = (99.99)

while price > 4.74:
    page = urllib.request.urlopen ("http://www.beans-r-us.biz/prices-loyalty.html")
    text = page.read().decode("utf8")

    where = text.find('>$')

    start_of_price = where + 2
    end_of_price = start_of_price + 6

    price = float(text[start_of_price:end_of_price])

print ("Buy!")

Here is my error:

Traceback (most recent call last):
  File "/Users/odin/Desktop/Coffe.py", line 14, in <module>
    price = float(text[start_of_price:end_of_price])
ValueError: invalid literal for float(): 4.59</
>>> 

What is wrong?

sth
  • 222,467
  • 53
  • 283
  • 367
Jeremy
  • 3
  • 2
  • Just a note: Learning Python 3.x is not recommended. I would switch to Python 2.5 or 2.6. They're not much different and there's more info/modules/tools out there for 2.x versions. – jjfine Apr 06 '10 at 18:38

2 Answers2

5

The problem is that you have extra characters at the end of your float, probably because the content of the page changed since the code was written (the number appears to change every fifteen minute). You could try changing the following line to make the code slightly more robust:

end_of_price = text.find('<', start_of_price)

For an even better solution you should use something like BeautifulSoup to parse the HTML.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • More precisely, why did you pick 6 in the line `end_of_price = start_of_price + 6`? In this case the size is 4, and it is possible that the size is not fixed. – Kathy Van Stone Apr 06 '10 at 17:50
  • 6 was used because when i used 4 for the previous assignment I only got the dollar amount and decimal, it did not give me the cents amount. – Jeremy Apr 06 '10 at 18:02
1

You are calculating end_of_price as start_of_price + 6. Actually your price value seems to be only 4 characters long, so that you also include the two characters following in the string you want to convert to a float. Python then complains that 4.59</ is not a number.

If you instead set end_of_price to start_of_price + 4 it should work.

sth
  • 222,467
  • 53
  • 283
  • 367
  • thank you. when I do as you say I now have this error Traceback (most recent call last): File "/Users/odin/Desktop/Coffe.py", line 14, in price = float(text[start_of_price:end_of_price]) ValueError: could not convert string to float: !DOC :( – Jeremy Apr 06 '10 at 17:51
  • I sent tried again and now it works? im not sure exactly what the problem is but as far and right this second it works. whos know about tomorrow... haha thank you so much sir, now i can continue this chapter! – Jeremy Apr 06 '10 at 17:56