У меня установлен Python 2.7, и я сталкиваюсь с ошибками при попытке запустить скрипты на Python. Приложение 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$
Кто-нибудь, пожалуйста, помогите мне с этим.
Вот тот, который работает:
from urllib import urlencode from urllib2 import urlopen try: #pg = urlopen("http://www.beans-r-us.biz/proces.html") pg = urlopen("http://beans.itcarlow.ie/prices.html") except: pg = False #if pg!=False: if pg: text = pg.read().decode("utf8") where = text.find(">$") start_of_price = where + 2 end_of_price = start_of_price + 4 try: price = float(text[start_of_price:end_of_price]) except: price = 'unknown. Some error happened parsing the price...' else: price = 'unknown. Some error happened while getting the url...' print "The current price of coffee is:", price
Небольшое улучшение в том, что он обрабатывает недействительный URL-адрес немного более изящно ... хотя не описательно.
изменить: изменить pg! = False для pg credit Jo . Он прав, что это чище. Я подумал, что для кого-то было бы более разумно скопировать код вставки, чтобы увидеть ложное изложение.
Вы абсолютно уверены, что правильно написали этот адрес? И что твое интернет соединение работает? Поскольку вы получаете ошибку HTTP 404, то есть ресурс не может быть найден, а не какая-то странная внутренняя ошибка Python.
Попробуйте это вместо:
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