getting value of location header using python urllib2

戏子无情 提交于 2019-12-06 10:46:01

Use the geturl method on the returned file-like object from urlopen:

>>> f = urllib2.urlopen('http://www.example.com')
>>> f.geturl()
'http://www.iana.org/domains/example/'
Joe

This is because by default urllib2 follows location headers. So the final response will not have one. If you disable following redirects suddenly you can see the location headers of 301 and 302 pages. See: How do I prevent Python's urllib(2) from following a redirect

Borrowing from there:

class NoRedirection(urllib2.HTTPErrorProcessor):
  def http_response(self, request, response):
    return response
  https_response = http_response

opener = urllib2.build_opener(NoRedirection)
location = opener.open('http://www.example.com').info().getheader('Location')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!