Python请求客户端错误:请求错误,但在浏览器中打开网站后工作 [英] Python Requests Client Error: Bad Request, but works after website has been opened in browser

查看:19
本文介绍了Python请求客户端错误:请求错误,但在浏览器中打开网站后工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,我收到了一个 400 客户端错误:对我从未打开过的 url 的错误请求,但是如果我用浏览器打开同一个 url 然后关闭它,我就是一个突然可以通过请求访问它.

I'm having a weird problem where I get a 400 Client Error: Bad Request on a url that I have never opened, but then if I open that same url with my browser and then close it, I am all of a sudden able to access it with Requests.

这是我的代码:

import requests
url = 'http://stats.nba.com/stats/boxscore?GameID=0021500669&RangeType=0&StartPeriod=0&EndPeriod=0&StartRange=0&EndRange=0'
response = requests.get(url)
response.raise_for_status() # raise exception if invalid response
data = response.json()['resultSets'][0]['rowSet']
print data

如果我在浏览器上访问网站之前运行它,我会收到此错误:

If I run this before visiting the website on a browser I receive this error:

Traceback (most recent call last):
File "stackOverflow.py", line 5, in <module>
response.raise_for_status() # raise exception if invalid response
File "C:Python27libsite-packages
equestsmodels.py", line 851, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request

但是在我访问 chrome 中的 url 然后再次运行它之后,我得到了我希望的列表.

But after I visit the url in chrome and then run it again I get the list I was hoping for.

我的第一个想法是 NBA 可能会阻止某些类型的请求,是这样吗?

My first thought is that maybe the NBA is blocking some types of requests, could that be it?

感谢您的帮助.

推荐答案

传递一个用户代理,它就会工作:

Pass a user-agent and it will work :

u_a = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"
response = requests.get(url, headers={"USER-AGENT":u_a})

这篇关于Python请求客户端错误:请求错误,但在浏览器中打开网站后工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆