不积跬步无以至千里,不积小流无以成江海

 Administrator     2022-06-05      小工具      1110

py脚本检查网址链接是否能够正常访问

最近项目需要检查网址是否能够访问,于是写了个python脚本

需要安装requests包,link2.txt格式如下

还需要创建一个空白的filename1.txt文件,方便写入数据。

具体代码如下:

import requests
import time
from requests.packages.urllib3.exceptions import InsecureRequestWarning

file = open('link2.txt',encoding='utf-8')
filename = open('filename1.txt',"r+",encoding='utf-8')

lines = file.readlines()
aa=[]
for line in lines:
	temp=line.split()[1].replace('\n','')
	aa.append(temp)
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# url = "https://learnku.com/dsdsd"
# r = requests.get(url,headers=headers,timeout=10,verify=False)
print('开始检查:')
for a in aa:
	# tempUrl = "http://"+a
	tempUrl = a
	try:
		requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
		r = requests.get(tempUrl,headers=headers,timeout=10,verify=False)
		if r.status_code == 200:
			print(tempUrl+' 没问题')
			filename.write(tempUrl+' 没问题\n')
		elif r.status_code == 302:
			print(tempUrl+' 转移至其他url')
			filename.write(tempUrl+' 转移至其他url\n')
		elif r.status_code == 307:
			print(tempUrl+' 转移至其他url')
			filename.write(tempUrl+' 转移至其他url\n')
		elif r.status_code == 404:
			print(tempUrl+' not found')
			filename.write(tempUrl+' not found\n')
		elif r.status_code == 500:
			print(tempUrl+' 服务器错误')
			filename.write(tempUrl+' not found\n')
		else:
			print(tempUrl+' 其他错误')	
			filename.write(tempUrl+' 其他错误\n')
	except requests.RequestException as e:
		print(tempUrl+' 访问出错')
		filename.write(tempUrl+' 访问出错\n')
		pass

filename.close()
time.sleep(0.1)

# print(r.status_code);