运行 Python 脚本时出错

运行 Python 脚本时出错

我安装了 Python 2.7,在尝试运行 Python 脚本时遇到错误。基于 GUI 的 Launchpad 应用 Ground Control 无法启动,并且存在错误。

但即使一个简单的程序也无法运行:

from urllib import urlencode
from urllib2 import urlopen

pg = urlopen("http://www.beans-r-us.biz/proces.html")

text = pg.read().decode("utf8")
where = text.find(">$")
start_of_price = where + 2
end_og_price = start_og_price + 4
price = float(text[start_of_price:end_of_price])

print "The current price of coffee is:", price

错误日志如下:

Traceback (most recent call last):
  File "androidscript.py", line 4, in <module>
    pg = urlopen("http://www.beans-r-us.biz/proces.html")
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 432, in error
    result = self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 619, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
anant@anant-Inspiron-N5010:~/Documents$

请有人帮助我。

答案1

这是一个有效的:

从 urllib 导入 urlencode
从 urllib2 导入 urlopen
尝试:
    #pg = urlopen("http://www.beans-r-us.biz/proces.html")
    pg = urlopen("http://beans.itcarlow.ie/prices.html")
除了:
    pg = 假
#如果 pg!=False:    
如果 pg:    
    文本 = pg.read().解码(“utf8”)
    其中 = 文本.查找(“>$”)
    起始价格 = 其中 + 2
    结束价格 = 起始价格 + 4
    尝试:
        价格 = 浮点数(文本[起始价格:结束价格])
    除了:
        price = '未知。解析价格时发生一些错误...'
别的:
    price = '未知。获取 URL 时发生一些错误...'
打印“咖啡的当前价格是:”,价格

稍有改进,它可以更加优雅地处理无效 URL...尽管不是描述性的。

编辑:将 pg!=False 更改为 pg 信用至。他说得对,这样更简洁。我认为如果有人复制粘贴代码来查看拼写出来的错误,可能会更有意义。

答案2

您确定您拼写的地址正确吗?您的互联网连接正常吗?因为您收到的错误是 HTTP 404,这意味着无法找到资源 —— 而不是一些奇怪的 Python 内部错误。

答案3

尝试一下这个:

from urllib import urlencode
from urllib2 import urlopen

pg = urlopen("http://www.beans-r-us.biz/prices.html")

text = pg.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 "The current price of coffee is:", price

相关内容