【问题标题】:Get content of http request as well as the response url in single request获取http请求的内容以及单个请求中的响应url
【发布时间】:2013-01-24 13:58:46
【问题描述】:

如何在单个请求中获取 http 响应的内容以及响应 url(不是请求的 url)。

为了得到我使用的响应:

from urllib2 import Request,urlopen
try:
    headers  = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US;)' }
    request  = Request(url, data, headers)
    print urlopen(request).read()
except Exception, e:
        raise Exception(e)

如果我只想要标题(标题将有响应 url),我使用了

try:
    headers  = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US;)' }
    request  = Request(url, data, headers)
request.get_method = lambda : 'HEAD'
    print urlopen(request).geturl()
    except Exception, e:
        raise Exception(e)

我正在发出两个请求以获取内容和网址。 我如何在一个请求中同时获得两者。如果我的函数将内容和 url 作为元组返回会更好。

【问题讨论】:

  • 我只需要响应 url,因为我请求的 url 可能会重定向到另一个页面。

标签: python http python-3.x http-headers urllib2


【解决方案1】:

如果您将urlopen(request) 分配给一个变量,您可以在一个请求中同时使用这两个属性

response = urlopen(request)
request_body = response.read()
request_url  = response.geturl()
print 'URL: %s\nRequest_Body: %s' % ( request_url, request_body )

【讨论】:

    【解决方案2】:

    我会把你的代码重构成这样的。我不知道你为什么要捕获异常只是为了再次引发它而不对它做任何事情。

    from urllib2 import Request,urlopen
    
    headers  = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US;)' }
    request  = Request(url, data, headers)
    request.get_method = lambda : 'GET'
    response = urlopen(request)
    return response.read(), response.get_url()
    

    如果您确实想捕获异常。你应该只把它放在urlopen 调用周围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-07
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      相关资源
      最近更新 更多