【Python】批量网站运行检测小工具

使用tkinter制作了图形界面的小工具,主要是通过requests获取网站的状态码200,获取到其他的状态码则判定为运行异常。
1、可自行输入检测文件位置,.txt(文本格式,一行一个网址)
2、可自行输入谷歌驱动程序位置,(驱动下载安装教程)
3、检测网站是否正常运行

# %%
#coding=utf-8

from selenium import webdriver
import tkinter as ck
from tkinter import ttk
import requests
import threading


#创建窗口
gjcss = ck.Tk()
gjcss.title("网站运行检测")
gjcss.geometry('600x350')

options = webdriver.ChromeOptions() # 设置中文
options.add_argument('lang=zh_CN.UTF-8') # 更换头部
options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"')# 请求响应标头


#URL文本
li1 = ck.Label(text="请输入文件名:", font=('Arial', 12)) 
li1.place(x=0, y=10)

#输入框
srk = ck.Entry(bd=2,width=30)
srk.insert(0,'wyurl.txt') 
srk.place(x=110, y=10)


#浏览器驱动
li2 = ck.Label(text="浏览器驱动:", font=('Arial', 12)) 
li2.place(x=0, y=40)

#输入框
srk2 = ck.Entry(bd=2,width=30)
srk2.place(x=110, y=40)


#创建表格
columns = ['序号', '网站名称', '网址','运行情况']
liebiao = ttk.Treeview(gjcss,columns=columns,show='headings')
liebiao.heading('序号', text='序号')
liebiao.heading('网站名称', text='网站名称')
liebiao.heading('网址', text='网址')
liebiao.heading('运行情况', text='运行情况')

liebiao.column('序号',width=50,anchor='s')
liebiao.column('网站名称',width=200,anchor='s')
liebiao.column('网址',width=200,anchor='s')
liebiao.column('运行情况',width=100,anchor='s')

# global i
# i = 0

def lqcz():
    global i
    i = 0
    
    getssc = srk.get()
    browsedriver = srk2.get()

    #打开谷歌浏览器
    #谷歌浏览器:C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chromedriver.exe
    # browser = webdriver.Chrome(r'%s' % (browsedriver),chrome_options=options)
    browser = webdriver.Chrome(r"C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chromedriver.exe",chrome_options=options)
    with open(getssc,"r",encoding='utf8') as f:#打开记事本
        for line in f.readlines():
            data = line.strip('\n') #去掉换行符
            try:
                browser.get(data)   #打开网址
                titlbt = browser.title  #获取网站标题
                weburl = requests.get(data)
                yxcode = weburl.status_code #获取状态码
                if  yxcode==200:
                    condition = '运行正常'
                else:
                    condition = '运行异常'  
                
            except:
                print ("Error:此无法网站打开",data)
                titlbt = '网站异常'
                condition = '运行异常'
            i += 1

            liebiao.insert('',0,text='date0',values=(i,titlbt,data,condition)) #向表格插入数据
#线程
def xc():            
    t = threading.Thread(target=lqcz)
    t.start()              
    # time1.sleep(10)

#wyurl.txt
antj = ck.Button(text="提交",width=10,command=xc)
antj.place(x=330, y=5)


# liebiao.insert('',0,text='date0',values=('1','网站名称','http://www.en.jixingchem.com','正常'))

liebiao.place(x=10, y=80)   #表格插入

vsb = ttk.Scrollbar(gjcss, orient="vertical", command=liebiao.yview)#Y轴滚动条
vsb.place(x=545, y=81, height=225)
liebiao.configure(yscrollcommand=vsb.set)



gjcss.mainloop()

在这里插入图片描述

更新内容 0.0.3

  1. 网址条数获取显示
  2. 界面优化
#coding=utf-8
import tkinter as tk
from tkinter import ttk
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import requests
import threading


class WebsiteHealthChecker:
    def __init__(self):
        # 初始化主窗口
        self.root = tk.Tk()
        self.root.title("网站运行检测")
        self.root.geometry('680x400')
        self.root.resizable(False, False)

        # 线程安全计数器
        self.counter = 0
        self.lock = threading.Lock()

        # 界面组件初始化
        self._init_ui()
        self._init_table()
        self._init_scrollbar()

    def _init_ui(self):
        """初始化界面组件"""
        # 文件输入部分
        tk.Label(self.root, text="请输入文件名:", font=('Arial', 12)).grid(row=0, column=0, sticky='w', padx=5, pady=5)
        self.file_entry = tk.Entry(self.root, width=40)
        self.file_entry.insert(0, 'wyurl.txt')
        self.file_entry.grid(row=0, column=1, sticky='w', padx=5, pady=5)

        # 驱动路径输入
        tk.Label(self.root, text="浏览器驱动:", font=('Arial', 12)).grid(row=1, column=0, sticky='w', padx=5, pady=5)
        self.driver_entry = tk.Entry(self.root, width=40)
        self.driver_entry.grid(row=1, column=1, sticky='w', padx=5, pady=5)

        # 提交按钮
        self.submit_btn = tk.Button(
            self.root, 
            text="开始检测", 
            width=15,
            command=self.start_checking
        )
        self.submit_btn.grid(row=0, column=2, rowspan=2, padx=10, pady=5)

        # 状态标签
        self.status_label = tk.Label(self.root, text="就绪", font=('Arial', 10), fg='gray')
        self.status_label.grid(row=2, column=0, columnspan=3, sticky='w', padx=5)

    def _init_table(self):
        """初始化结果表格"""
        columns = ['序号', '网站名称', '网址', '运行情况']
        self.result_table = ttk.Treeview(
            self.root,
            columns=columns,
            show='headings',
            height=12
        )

        # 配置列参数
        column_config = {
            '序号': {'width': 60, 'anchor': 'center'},
            '网站名称': {'width': 200, 'anchor': 'w'},
            '网址': {'width': 250, 'anchor': 'w'},
            '运行情况': {'width': 100, 'anchor': 'center'}
        }

        for col in columns:
            self.result_table.heading(col, text=col)
            self.result_table.column(col, **column_config[col])

        self.result_table.grid(row=3, column=0, columnspan=3, padx=10, pady=10, sticky='nsew')

    def _init_scrollbar(self):
        """初始化滚动条"""
        scrollbar = ttk.Scrollbar(
            self.root,
            orient="vertical",
            command=self.result_table.yview
        )
        scrollbar.grid(row=3, column=3, sticky='ns')
        self.result_table.configure(yscrollcommand=scrollbar.set)

    def _update_status(self, message, color='gray'):
        """更新状态栏"""
        self.status_label.config(text=message, fg=color)

    def _get_driver_path(self):
        """获取浏览器驱动路径"""
        driver_path = self.driver_entry.get().strip()
        if not driver_path:
            return r"C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chromedriver.exe"
        return driver_path

    def _check_website(self, url, driver_path):
        """检测单个网站状态"""
        try:
            # 使用requests获取状态码
            response = requests.get(url, timeout=10)
            status_code = response.status_code
            status = '正常' if status_code == 200 else f'异常({status_code})'
            
            # 使用Selenium获取页面标题
            options = webdriver.ChromeOptions()
            options.add_argument('--headless')  # 无头模式
            options.add_argument('lang=zh_CN.UTF-8')
            options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"')

            with webdriver.Chrome(executable_path=driver_path, options=options) as driver:
                driver.get(url)
                title = driver.title or '无标题'

        except requests.RequestException as e:
            status = f'请求失败 ({str(e)})'
            title = '连接异常'
        except WebDriverException as e:
            status = f'浏览器错误 ({str(e)})'
            title = '驱动异常'
        except Exception as e:
            status = f'未知错误 ({str(e)})'
            title = '检测异常'

        # 更新计数器
        with self.lock:
            self.counter += 1
            current_count = self.counter

        # 更新表格(需要在主线程执行)
        self.root.after(0, self._update_table, [
            current_count,
            title,
            url,
            status
        ])

    def _update_table(self, row_data):
        """更新表格数据"""
        self.result_table.insert('', 'end', values=row_data)
        self.result_table.yview_moveto(1)  # 自动滚动到底部

    def start_checking(self):
        """启动检测任务"""
        # 重置状态
        self.counter = 0
        self.result_table.delete(*self.result_table.get_children())
        self.submit_btn.config(state='disabled')
        self._update_status('检测进行中...', 'blue')

        # 获取输入参数
        file_path = self.file_entry.get()
        driver_path = self._get_driver_path()

        # 读取URL文件
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                urls = [line.strip() for line in f if line.strip()]
        except FileNotFoundError:
            self._update_status('错误:文件不存在!', 'red')
            self.submit_btn.config(state='normal')
            return
        except Exception as e:
            self._update_status(f'读取文件失败:{str(e)}', 'red')
            self.submit_btn.config(state='normal')
            return

        # 创建检测线程
        for url in urls:
            thread = threading.Thread(
                target=self._check_website,
                args=(url, driver_path),
                daemon=True
            )
            thread.start()

        # 启动完成检查线程
        threading.Thread(
            target=self._monitor_threads,
            args=(len(urls),),
            daemon=True
        ).start()

    def _monitor_threads(self, total):
        """监控线程完成情况"""
        while self.counter < total:
            continue
        
        self.root.after(0, self._finalize_checking)

    def _finalize_checking(self):
        """完成检测后的清理"""
        self.submit_btn.config(state='normal')
        self._update_status(f'检测完成,共检测{self.counter}个网站', 'green')

    def run(self):
        self.root.mainloop()


if __name__ == '__main__':
    app = WebsiteHealthChecker()
    app.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值