python urlopen返回的是啥类型,python的urlib2判断web服务器返回资源的类型

一般情况下,我们从网络上抓资源会这样写代码:

try:

request = urllib2.Request(url)

response = urllib2.urlopen(request, timeout = 10)

except:

print traceback.format_exc()

content = cStringIO.StringIO(response.read())

但是网络上的资源有很多的不确定性。比如,我想抓取一个图片文件,但是服务器因为内部错误返回一串字符串;或者返回一个error code。

因此这要求我们在读取内容之前,需要判断一下某些状态是否正确。例如:

response = None

try:

request = urllib2.Request(url)

response = urllib2.urlopen(request, timeout = 10)

except:

print traceback.format_exc()

# 判断返回码是否是正常

if response.code < 200 or response.code >= 300:

print "some error found"

# 判断content type是不是image的

if response.headers.type is not None and response.headers.type.find("image") != -1:

print "this is an image resource"

else:

print "not an image"

# 再读取资源

content = cStringIO.StringIO(response.read())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值