2013-10-29 82 views
0

當我在程序中使用float()方法時,出現錯誤。你能幫我解決這個問題嗎?我正在使用python 3.4.0a4。python中的回溯錯誤

這是程序:

import urllib.request 

price = 99.99 
while price > 4.74: 
    page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html") 
    text = page.read().decode("utf8") 
    where = text.find('>$') 
    start_of_price = where + 2 
    end_of_price = start_of_price + 4 
    price = float(text[start_of_price:end_of_price]) 
Print("Buy!") 

,這是錯誤我得到:

Traceback (most recent call last): 
    File "F:/Python/python 8.py", line 11, in <module> 
    price = float(text[start_of_price:end_of_price]) 
ValueError: could not convert string to float: '!DOC' 
+5

您發現錯誤的'> $'。如果您正在解析HTML,請考慮使用HTML解析器,例如BeautifulSoup。 –

+1

除非你預先定義了'Print',否則你會在最後一行得到'NameError',因爲它應該是'print'。請記住Python區分大小寫。 – iCodez

+0

您的切片字符串「text [start_of_price:end_of_price]」不是數字。 – aIKid

回答

0

好像你在錯誤的位置切網頁的字符串,並將結果text[start_of_price:end_of_price]!DOC

這不是一個有效的數字,因此不能轉換爲浮點數。

0

這是Head First Programming中給出的確切代碼。鏈接被打破,我得到了糾正它的輸出。感謝您的幫助..