获取http请求的内容以及单个请求中的响应url

2024-05-12 10:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在单个请求中获取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。 我怎么能在一个请求中同时得到这两个。如果我的函数以元组形式返回content&url,那会更好。


Tags: urlmozilla内容requestlinuxexceptionagenturlopen
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调用的周围。

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

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

相关问题 更多 >