python中使用urllib2获取http请求状态码的代码例子,pythonurllib2


采集内容常需要得到网页返回的验证码做进一步处理

下面代码是用python写的用来获取网页http状态码的脚本

#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
#Filename:states_code.py
 
import urllib2
 
url = 'http://www.bkjia.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()


python urllib2中http问题

只有try无异常发生时,才会print 2,你说从不执行print 2,说明try代码块中有问题
 

python里,怎获取返回码非200的网页源码?

非200的不一定会有源码。你可以参看RFC2616的说明,比如302、301你就去再请求header中Location的url,5xx你就可以放弃,等等……
 

评论关闭