使用python批量检查url的有效性

因为工作需要,之前用python写了一些批量校验url有效性的小脚本,但并不全面,健壮性较差,现把之整理一下,代码如下:

#!/usr/bin/python
# -*- coding:utf-8 -*-

import urllib2
from urllib2 import URLError

result_url=[]
count=0
not_200=0
f=open("img1.txt","r")
img_not_200=open("img_not_200.txt","w+")

for line in f:
    count+=1
    print "on scanning ",count
    try:
    	response=urllib2.urlopen(line)
    except URLError, e:
    	if hasattr(e,'reason'): #stands for URLError
    		print "can not reach a server,writing..."
    		result_url.append(line)
    		not_200+=1
    		img_not_200.write(line)
    		print "write url success!"
    	elif hasattr(e,'code'): #stands for HTTPError
    		print "find http error, writing..."
    		result_url.append(line)
    		not_200+=1
    		img_not_200.write(line)
    		print "write url success!"
    	else: #stands for unknown error
    		print "unknown error, writing..."
    		result_url.append(line)
    		not_200+=1
    		img_not_200.write(line)
    		print "write url success!"
    else:
    	#print "url is reachable!"
    	#else 中不用再判断 response.code 是否等于200,若没有抛出异常,肯定返回200,直接关闭即可
    	response.close()
    finally:
    	pass

print "scanning over,total",count,"; did not response 200:",not_200
f.close()
img_not_200.close()

对这段代码解析如下:

如果url有效,则可以正常通过urlopen取到response,并且response.getcode()等于200;

但若url无效,无论是无法找到服务器还是其他http错误,都无法通过urlopen返回response。这个时候,就需要通过返回的错误类型来判断错误到底是url错误还是http错误。上面的程序是通过错误类型所拥有的属性来判断的。如果错误类型有“code”属性,则代表错误是HTTPError;如果属性有“reason”,则代表是URLError错误。

当然,也可以在except中分别指定抛出的错误类型,进而进行不同的处理。所要注意的是,因为HTTPError是URLError的子类,所以必须在第一个except中指定捕获HTTPError,第二个except中指定捕获URLError,否则的话,你懂的。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值