最近有一个批量检测 URL 是否可以访问的需求,于是找了一个 Python 脚本来实现这个需求( Python 2.7+ 测试有效)。
参考原文
https://ccie.lol/knowledge-base/python-testing-url-2/
这个脚本会对每个 URL 检测四次,其中 http 检测两次,https 检测两次。之所以是各两次是因为会使用两个包来检测( urllib 和 urllib2 )。即:
urllib 检测 http
urllib 检测 https
urllib2 检测 http
urllib2 检测 https
共四次。
首先是包的导入和浏览器所使用的 User-Agent 的定义:
# coding=utf-8
import httplib, urllib, urllib2, ssl, time, os, threading
HEADERS = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3298.4 Safari/537.36'}
因为增加了多线程,所以多引入了一个名为 threading 的包。
紧接着是 show_status_urllib(url) 和 show_status_urllib2(url) 两个检测方法,这里面捕获了大量的异常;以及一个用于处理所返回的网页状态码的函数 return_code(function_name, response) :
def show_status_urllib(url):
function_name = 'urllib'
try:
response = urllib.urlopen(url)
except IOError, e:
return False, function_name + ' : IOError - ' + e.message
except ssl.CertificateError, e:
return False, function_name + ' : CertificateError - ' + e.message
except httplib.BadStatusLine, e:
return False, function_name + ' : httplib.BadStatisLine - ' + e.message
else:
return return_code(function_name, response)
def show_status_urllib2(url):
function_name = 'urllib2'
try:
# request = urllib2.Request(url)
request = urllib2.Request(url, '', HEADERS)
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
return False, function_name + ' : HTTPError code ' + str(e.code)
except urllib2.URLError, e:
return False, function_name + ' : URLError - ' + str(e.reason)
ex