使用python获取http响应代码

使用python获取http响应代码,python,http,Python,Http,我知道如何使用httplib实现这一点,但我还需要设置用户代理,我确信您需要urllib来实现这一点。如何使用urllib获取http响应代码?您可以使用urllib2中的.getcode()获取http代码: urllib2.urlopen("http://google.com").getcode() 带有的完整标题以列表形式出现在info()中: urllib2.urlopen("http://google.com").info().headers 实际上,httplib允许设置用户代理

我知道如何使用httplib实现这一点,但我还需要设置用户代理,我确信您需要urllib来实现这一点。如何使用urllib获取http响应代码?

您可以使用urllib2中的
.getcode()
获取http代码:

urllib2.urlopen("http://google.com").getcode()
带有的完整标题以列表形式出现在
info()
中:

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

实际上,httplib允许设置用户代理

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

>>>urllib2.urlopen(“回溯(最近一次调用):urllib2.urlopen中的文件“”,第1行)(“AttributeError:HTTPMessage实例没有属性'getcode',我认为第一行代码应该是
urllib2.urlopen(”http://google.com“”。getcode()