python/urllib2/ target=_blank class=infotextkey>python urllib2模块获取http请求状态码
采集内容经常需要得到网页返回的验证码,以做进一步处理。
例子,python获取网页http状态码的脚本。
复制代码 代码示例:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
#Filename:states_code.py
import urllib2
url = 'http://www.jb200.com/'
response = None
try:
response = urllib2.urlopen(url,timeout=5)
except urllib2.URLError as e:
if hasattr(e, 'code'):
print 'Error code:',e.code
elif hasattr(e, 'reason'):
print 'Reason:',e.reason
finally:
if response:
response.close()
以上代码使用urllib2库取得www.jb200.com的网页状态码。