从 pythonanywhere 打开 url

open url from 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

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

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

我最近将 urllib2 与 pythonanywhere 上的一个烧瓶项目一起使用,使用他们的免费帐户访问 donorschoose.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)

这确实有效。

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

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