且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 urllib2.urlopen 时如何获取最终重定向 URL?

更新时间:2023-11-26 17:10:58

调用返回的文件对象的 .geturl() 方法.根据 urllib2 文档:

Call the .geturl() method of the file object returned. Per the urllib2 docs:

geturl() — 返回检索到的资源的 URL,通常用于确定是否遵循重定向

geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed

示例:

import urllib2
response = urllib2.urlopen('http://tinyurl.com/5b2su2')
response.geturl() # 'http://***.com/'