当服务器使用 urllib2.urlopen(url).geturl() 重定向我时,我无法获得整个 url

I can not get the whole url when the server redirect me by using urllib2.urlopen(url).geturl()

例如,如果整个 url是'http://www.whosebug.com?key=value&key1=value1',我只能得到'http://www.whosebug.com'

urllib2 在重定向后删除查询字符串:

>>> import urllib2
>>> r = urllib2.urlopen('http://httpbin.org/redirect-to?url=http://example.com/%3Ffoo=bar')
>>> r.geturl()
'http://example.com/?foo=bar'

也许您使用的网站会根据带有查询字符串的请求再次 重定向您?

您可以改用 requests library;您可以完全禁用重定向,也可以反省重定向的历史记录:

>>> import requests 
>>> r = requests.get('http://httpbin.org/relative-redirect/4')
>>> r.history
[<Response [302]>, <Response [302]>, <Response [302]>, <Response [302]>]
>>> r.history[2].url
u'http://httpbin.org/relative-redirect/2'