从pythonanywhere

时间:2015-09-15 23:39:07

标签: python urllib2 pythonanywhere

此代码在我的本地计算机上运行良好,但是当我在pythonanywhere.com上传并运行它时,它会给我这个错误。
我的代码:

url = "http://www.codeforces.com/api/contest.list?gym=false"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
                'Accept-Encoding': 'none',
                'Accept-Language': 'en-US,en;q=0.8',
                'Connection': 'keep-alive'}
         req = urllib2.Request(url, headers=hdr)
         opener = urllib2.build_opener()
         openedReq = opener.open(req, timeout=300)

错误:

Traceback (most recent call last):
File "/home/GehadAbdallah/main.py", line 135, in openApi
    openedReq = opener.open(req, timeout=300)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

P.S。我正在使用python 2.7

3 个答案:

答案 0 :(得分:5)

PythonAnywhere上的免费帐户仅限于whitelist个网站,仅限http / https,访问权限通过代理进行。这里有更多信息:

PythonAnywhere wiki: "why do I get a 403 forbidden error when opening a url?"

答案 1 :(得分:1)

我最近在pythonany上使用urllib2和一个烧瓶项目,使用他们的免费帐户访问donorchoose.org上的api

这可能会有所帮助,

@app.route('/funding')
def fundingByState():
    urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler({'http': 'proxy.server:3128'})))
    donors_choose_url = "http://api.donorschoose.org/common/json_feed.html?historical=true&APIKey=DONORSCHOOSE"
    response = urllib2.urlopen(donors_choose_url)
    json_response = json.load(response)
    return json.dumps(json_response)

这确实有效。

答案 2 :(得分:0)

如果您使用付费帐户但仍会收到此错误消息 试试这个pythonanywhere_forums

对我来说,我必须删除控制台,然后重新启动一个新控制台。