python 请求处理错误 302?
python requests handle error 302?
我正在尝试使用 requests
库向重定向 url 发出 http 请求(作为响应 headers-Location)。使用 Chrome 检查时,我可以看到响应状态为 302。
但是,在 python 中,requests
总是 returns 200 状态。我添加了 allow_redirects=False
,但状态仍然始终是 200。
- url是
https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679
- 第一行输入测试账号:
moyan429@hotmail.com
- 第二行输入密码:
112358
然后点击第一个按钮登录。
我的Python代码:
import requests
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36'
session = requests.session()
session.headers['User-Agent'] = user_agent
session.headers['Host'] = 'api.weibo.com'
session.headers['Origin']='https://api.weibo.com'
session.headers['Referer'] ='https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679'
session.headers['Connection']='keep-alive'
data = {
'client_id': api_key,
'redirect_uri': callback_url,
'userId':'moyan429@hotmail.com',
'passwd': '112358',
'switchLogin': '0',
'action': 'login',
'response_type': 'code',
'quick_auth': 'null'
}
resp = session.post(
url='https://api.weibo.com/oauth2/authorize',
data=data,
allow_redirects=False
)
code = resp.url[-32:]
print code
您可能收到 API 错误消息。使用print resp.text
看看服务器告诉你这里有什么错误。
请注意,您可以随时检查 resp.history
以查看是否存在任何重定向;如果有的话,您会找到一个响应列表 objects。
不设置Host
或Connection
header;将这些留给 requests
处理。我怀疑这里是否需要 Origin
或 Referer
header。由于这是一个 API,因此 User-Agent
header 可能也有点矫枉过正了。
我正在尝试使用 requests
库向重定向 url 发出 http 请求(作为响应 headers-Location)。使用 Chrome 检查时,我可以看到响应状态为 302。
但是,在 python 中,requests
总是 returns 200 状态。我添加了 allow_redirects=False
,但状态仍然始终是 200。
- url是
https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679
- 第一行输入测试账号:
moyan429@hotmail.com
- 第二行输入密码:
112358
然后点击第一个按钮登录。
我的Python代码:
import requests
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36'
session = requests.session()
session.headers['User-Agent'] = user_agent
session.headers['Host'] = 'api.weibo.com'
session.headers['Origin']='https://api.weibo.com'
session.headers['Referer'] ='https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679'
session.headers['Connection']='keep-alive'
data = {
'client_id': api_key,
'redirect_uri': callback_url,
'userId':'moyan429@hotmail.com',
'passwd': '112358',
'switchLogin': '0',
'action': 'login',
'response_type': 'code',
'quick_auth': 'null'
}
resp = session.post(
url='https://api.weibo.com/oauth2/authorize',
data=data,
allow_redirects=False
)
code = resp.url[-32:]
print code
您可能收到 API 错误消息。使用print resp.text
看看服务器告诉你这里有什么错误。
请注意,您可以随时检查 resp.history
以查看是否存在任何重定向;如果有的话,您会找到一个响应列表 objects。
不设置Host
或Connection
header;将这些留给 requests
处理。我怀疑这里是否需要 Origin
或 Referer
header。由于这是一个 API,因此 User-Agent
header 可能也有点矫枉过正了。