and*_*ngo 5 python json ipython http-error python-requests
当我在 iPython (Python 2.7) 中运行此代码时:
from requests import get
_get = get('http://stats.nba.com/stats/playergamelog', params={'PlayerID': 203083, 'Season':'2015-16', 'SeasonType':'Regular Season'})
print _get.url
_get.raise_for_status()
_get.json()
Run Code Online (Sandbox Code Playgroud)
我正进入(状态:
http://stats.nba.com/stats/playergamelog?PlayerID=203083&Season=2015-16&SeasonType=Regular+Season
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
<ipython-input-5-8f8343b2c4cd> in <module>()
1 _get = get('http://stats.nba.com/stats/playergamelog', params={'PlayerID': 203083, 'Season':'2015-16', 'SeasonType':'Regular Season'})
2 print _get.url
----> 3 _get.raise_for_status()
4 _get.json()
/Library/Python/2.7/site-packages/requests/models.pyc in raise_for_status(self)
849
850 if http_error_msg:
--> 851 raise HTTPError(http_error_msg, response=self)
852
853 def close(self):
HTTPError: 400 Client Error: Bad Request
Run Code Online (Sandbox Code Playgroud)
但是,如果我在浏览器中访问该 url,它就可以工作。然后,当我回到代码并在我的浏览器(运行 iPython 的 Chrome)中手动访问 URL 后再次运行它时,代码运行没有错误。但是,它可能会返回到在顺序执行中引发错误。
这段代码已经为我工作了数百次,甚至数千次都没有问题。我该如何解决这个错误?
谢谢。
HTTPError: 400 Client Error: Bad Request表示您提出的请求有错误。我认为服务器可能会检查 HTTP 请求中的某些标头,例如user-agent.
所以我尝试设置 User-Agent 标头来模仿 Firefox:
# No User-Agent
>>> _get = get('http://stats.nba.com/stats/playergamelog', params={'PlayerID': 203082, 'Season':'2015-16', 'SeasonType':'Regular Season'})
>>> _get.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\requests\models.py", line 840, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http://stats.nba.com/stats/playergamelog?PlayerID=203082&Season=2015-16&SeasonType=Regular+Season
# This time, set user-agent to mimic a desktop browser
>>> headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'}
>>> _get = get('http://stats.nba.com/stats/playergamelog', params={'PlayerID': 203082, 'Season':'2015-16', 'SeasonType':'Regular Season'}, headers=headers)
>>> _get.raise_for_status()
>>>
# no error
Run Code Online (Sandbox Code Playgroud)
它之所以能够在浏览器中访问 URL 后起作用,是因为缓存。
根据 Alastair McCormack 的说法,stats.nba.com它以 Akamai CDN 为前端,因此缓存可能发生在边缘,通过查询字符串/URI 而不是无关的标头“变化”。一旦对该 URI 做出有效响应,该响应就会被服务于该客户端的 CDN 边缘节点缓存。
因此,当您在浏览器中访问 url 后运行代码时,CDN 将返回缓存的响应。在这种情况下不会筹集到400。
| 归档时间: |
|
| 查看次数: |
14584 次 |
| 最近记录: |