用python获取http响应代码

时间:2010-08-16 08:04:14

标签: python http

我知道如何使用httplib执行此操作,但我还需要设置用户代理,并且我确定您需要urllib来执行此操作。如何使用urllib获取http响应代码?

2 个答案:

答案 0 :(得分:5)

您可以在urllib2中使用.getcode()来获取HTTP代码:

urllib2.urlopen("http://google.com").getcode()

完整标题位于info()列表中:

urllib2.urlopen("http://google.com").info().headers

答案 1 :(得分:0)

实际上,httplib允许设置User-Agent。

headers = { 'User-Agent' : 'someapp', 'Content-Type' : 'text/html' }  
conn = httplib.HTTPConnection(host, port)  
conn.request('POST', '/foobar', 'mydata', headers)
相关问题