Python urllib2响应头 [英] Python urllib2 Response header

查看:132
本文介绍了Python urllib2响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图提取URL请求的响应头。当我使用firebug分析URL请求的响应输出时,它会返回:

I'm trying to extract the response header of a URL request. When I use firebug to analyze the response output of a URL request, it returns:

Content-Type text/html

然而,当我使用python代码时:

However when I use the python code:

urllib2.urlopen(URL).info()

结果输出返回:

Content-Type: video/x-flv

我对python和一般的web编程都很陌生;任何有用的见解,非常感谢。此外,如果需要更多信息,请让我知道。

I am new to python, and to web programming in general; any helpful insight is much appreciated. Also, if more info is needed please let me know.

感谢您阅读本文

推荐答案

尝试像Firefox那样请求。您可以在Firebug中看到请求标题,因此将它们添加到您的请求对象中:

Try to request as Firefox does. You can see the request headers in Firebug, so add them to your request object:

import urllib2

request = urllib2.Request('http://your.tld/...')
request.add_header('User-Agent', 'some fake agent string')
request.add_header('Referer', 'fake referrer')
...
response = urllib2.urlopen(request)
# check content type:
print response.info().getheader('Content-Type')

还有HTTPCookieProcessor,它可以让它变得更好,但我不认为大多数情况下你都需要它。看看python的文档:

There's also HTTPCookieProcessor which can make it better, but I don't think you'll need it in most cases. Have a look at python's documentation:

http ://docs.python.org/library/urllib2.html

这篇关于Python urllib2响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆