2018年8月28日 星期二

[ Python 常見問題 ] Python Requests library redirect new url

Source From Here 
Question 
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve. In my script I am setting allow_redirects=True. I would like to know if the page has been redirected to something else, what is the new URL. 
For example, if the start URL was: www.google.com/redirect 
And the final URL is www.google.co.uk/redirected 

How do I get that URL? 

How-To 
You are looking for the request history. The response.history attribute is a list of responses that led to the final URL, which can be found in response.url: 
  1. response = requests.get(someurl)  
  2. if response.history:  
  3.     print "Request was redirected"  
  4.     for resp in response.history:  
  5.         print resp.status_code, resp.url  
  6.     print "Final destination:"  
  7.     print response.status_code, response.url  
  8. else:  
  9.     print "Request was not redirected"  
A real demo as below: 
>>> import requests 
>>> response = requests.get('http://httpbin.org/redirect/3') 
>>> for resp in response.history: 
... print("{}\t{}".format(resp.status_code, resp.url)) 
... 
302 http://httpbin.org/redirect/3 
302 http://httpbin.org/relative-redirect/2 
302 http://httpbin.org/relative-redirect/1
 
>>> print("Final URL={} with status code = {}".format(response.url, response.status_code)) 
Final URL=http://httpbin.org/get with status code = 200


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...