Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get original url from requests

In doing the following:

>>> res=requests.get('http://www.hulu.com/return-of-the-one-armed-swordsman')
>>> res.url
u'http://www.hulu.com/watch/800769'

How would I get the original url that was called from res. That is, how would I get the res object to return http://www.hulu.com/return-of-the-one-armed-swordsman?

like image 270
David542 Avatar asked Jun 06 '15 21:06

David542


People also ask

What does requests get url do?

The get() method sends a GET request to the specified url.

How do I get the url in Python?

You can get the current url by doing path_info = request. META. get('PATH_INFO') http_host = request.

How do you get responses in Python?

This Response object in terms of python is returned by requests. method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.


1 Answers

requests keeps a history of redirect requests... Take the first entry from that...

import requests

res=requests.get('https://httpbin.org/status/301')
res.url
# https://httpbin.org/get
res.history[0].url
# https://httpbin.org/status/301

Note - you might want to cater for where no redirects occured, eg:

url = res.history[0].url if res.history else res.url

Of course -the other way is to just keep your URL in a variable and pass that to requests.get - then you know what you asked for to start with...

like image 144
Jon Clements Avatar answered Oct 19 '22 14:10

Jon Clements