前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >使用python批量检查url的有效性

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

作者头像
py3study
发布2020-01-08 11:11:38
发布2020-01-08 11:11:38
4.2K00
代码可运行
举报
文章被收录于专栏:python3python3
运行总次数:0
代码可运行

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

代码语言:javascript
代码运行次数:0
运行
复制
#!/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,否则的话,你懂的。。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档