如何使用python请求获取重定向url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36070821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:21:54  来源:igfitidea点击:

how to get redirect url using python requests

pythonpython-requests

提问by 1a1a11a

r = requests.get('http://techtv.mit.edu/videos/1585-music-session-02/download.source') 
for i in r.history:
    print(i.url) 

I think it should print out the history, but it doesn't, the above url points to a video, but I cannot get it, anyone help? Thank you

我认为它应该打印出历史记录,但它没有,上面的 url 指向一个视频,但我无法得到它,有人帮忙吗?谢谢

回答by Aaron Christiansen

To get the resultant URL after you've been redirected, you can do r.url.

要在重定向后获取结果 URL,您可以执行r.url.

r = requests.get('http://techtv.mit.edu/videos/1585-music-session-02/download.source') 
print(r.url) # http://d1baxxa0joomi3.cloudfront.net/2515a9db659b0ab26d869b4ff2dadca9/original.mov

r.historyis for URLs prior to the final one, so it's only returning your original URL because you were only redirected once.

r.history用于最后一个之前的 URL,因此它只返回您的原始 URL,因为您只被重定向一次。