【问题标题】:I can not get the whole url when the server redirect me by using urllib2.urlopen(url).geturl()当服务器使用 urllib2.urlopen(url).geturl() 重定向我时,我无法获取整个 url
【发布时间】:2015-03-10 17:01:29
【问题描述】:

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

【问题讨论】:

    标签: python urllib2


    【解决方案1】:

    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'
    

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2013-08-06
      • 1970-01-01
      • 2019-02-07
      相关资源
      最近更新 更多