python requests handle error 302?
You are probably getting an API error message. Use print resp.text
to see what the server tells you is wrong here.
Note that you can always inspect resp.history
to see if there were any redirects; if there were any you'll find a list of response objects.
Do not set the Host
or Connection
headers; leave those to requests
to handle. I doubt the Origin
or Referer
headers here needed either. Since this is an API, the User-Agent
header is probably also overkill.
Guixing Wei
Updated on June 04, 2022Comments
-
Guixing Wei almost 2 years
I am trying to make a http request using
requests
library to the redirect url (in response headers-Location). When using Chrome inspection, I can see the response status is 302.However, in python,
requests
always returns a 200 status. I added theallow_redirects=False
, but the status is still always 200.- The url is
https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679
- the first line entered the test account:
[email protected]
- the second line entered the password:
112358
and then click the first button to login.
My Python code:
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':'[email protected]', '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
- The url is
-
Guixing Wei almost 9 yearsthanks for your response. I checked the resp.history, it's empty. and the content of resp.text showed that it still stay in the same page. But when I used browser to login this url, the redirect will happen.
-
Martijn Pieters almost 9 years@GuixingWei: so you are missing something else. Perhaps the page uses CSRF tokens? Perhaps you need to
GET
the login page first to get the session cookie? -
Guixing Wei almost 9 yearsappreciate a lot for your suggestion. I fixed this problem. Yes,your idea is right. I need to get the cookie from login page, and then use the cookie to get the authorization page. Thanks so much for this idea!!