使用selenium从CNAS网站解析实验室信息

#!/usr/bin/env python3

-- coding: utf-8 --

"""

CNAS查询结果保存脚本

使用说明:

  1. 脚本将自动打开Chrome浏览器并访问CNAS查询网站
  2. 请您在浏览器中手动输入搜索内容并提交查询
  3. 搜索完成后,请您手动点击要查看的链接,打开弹出网页
  4. 脚本将自动检测新窗口,并将其内容保存为xlsx文件
  5. 保存完成后,按回车键退出程序

依赖安装:

pip install selenium webdriver-manager pandas beautifulsoup4 openpyxl

"""

尝试导入必要的模块

try:

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

from selenium.webdriver.chrome.service import Service

from webdriver_manager.chrome import ChromeDriverManager

import pandas as pd

from bs4 import BeautifulSoup

import datetime

import time

import re

except ModuleNotFoundError as e:

print(f"错误: 未找到模块 - {e}")

print("请先安装依赖: pip install selenium webdriver-manager pandas beautifulsoup4 openpyxl")

print("然后再次运行脚本")

exit(1)

设置Chrome选项

CHROME_OPTIONS = Options()

CHROME_OPTIONS.add_argument("--start-maximized")

CHROME_OPTIONS.add_argument("--disable-blink-features=AutomationControlled")

CHROME_OPTIONS.add_argument(

"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

保存内容为xlsx文件的函数

def save_to_excel(driver, window_handle):

"""将网页内容保存为xlsx文件,包括所有表格和完整页面文本"""

切换到目标窗口

driver.switch_to.window(window_handle)

print(f"\n=== 处理窗口: {driver.title} ===")

复制代码
# 获取页面内容
page_content = driver.page_source

# 解析页面
soup = BeautifulSoup(page_content, "html.parser")

# 提取页面标题
page_title = soup.title.string.strip() if soup.title else "无标题"
print(f"页面标题: {page_title}")

# 提取页面中的表格
tables = soup.find_all("table")
print(f"找到 {len(tables)} 个表格")

# 提取完整页面文本
text_content = soup.get_text()
cleaned_text = re.sub(r'\s+', ' ', text_content).strip()
print(f"页面文本长度: {len(cleaned_text)} 字符")

# 生成文件名
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"cnas_result_{timestamp}.xlsx"

# 创建Excel写入器
with pd.ExcelWriter(filename, engine="openpyxl") as writer:
    # 1. 保存完整页面文本到专门的工作表
    text_df = pd.DataFrame({
        "页面标题": [page_title],
        "页面完整内容": [cleaned_text]
    })
    text_df.to_excel(writer, sheet_name="页面文本", index=False)
    print("已保存完整页面文本到工作表: 页面文本")

    # 2. 保存所有表格到不同的工作表
    for i, table in enumerate(tables):
        try:
            # 使用pandas读取表格
            df = pd.read_html(str(table))[0]

            # 设置工作表名称
            sheet_name = f"表格{i + 1}"
            if len(sheet_name) > 31:  # Excel工作表名称不能超过31个字符
                sheet_name = sheet_name[:31]

            # 保存表格到工作表
            df.to_excel(writer, sheet_name=sheet_name, index=False)
            print(f"已保存第 {i + 1} 个表格到工作表: {sheet_name}")
        except Exception as e:
            print(f"处理第 {i + 1} 个表格失败: {e}")

    # 3. 保存页面元信息
    meta_df = pd.DataFrame({
        "项目": ["页面标题", "URL", "保存时间", "表格数量", "页面文本长度"],
        "值": [
            page_title,
            driver.current_url,
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            len(tables),
            len(cleaned_text)
        ]
    })
    meta_df.to_excel(writer, sheet_name="元信息", index=False)
    print("已保存页面元信息到工作表: 元信息")

print(f"\n所有内容已成功保存到文件: {filename}")
print(f"文件包含: 1个页面文本工作表 + {len(tables)}个表格工作表 + 1个元信息工作表")
return filename

主程序

def main():

"""主函数"""

print("CNAS查询结果保存脚本")

print("=" * 50)

print("使用步骤:")

print("1. 脚本将自动打开Chrome浏览器并访问CNAS查询网站")

print("2. 请您在浏览器中手动输入搜索内容并提交查询")

print("3. 搜索完成后,请您手动点击要查看的链接,打开弹出网页")

print("4. 脚本将自动检测新窗口,并将其内容保存为xlsx文件")

print("5. 保存完成后,按回车键退出程序")

print("=" * 50)

复制代码
# 初始化WebDriver
print("正在初始化浏览器...")
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=CHROME_OPTIONS)

# 保存原始窗口句柄
original_window = driver.current_window_handle

try:
    # 访问目标URL
    url = "https://www.cnas.org.cn/sfcxxt/index.html?tpl=/LAS_FQ/publish/externalQueryL1.jsp&name=%E8%8E%B7%E8%AE%A4%E5%8F%AF%E6%A3%80%E6%B5%8B%E5%92%8C%E6%A0%A1%E5%87%86%E5%AE%9E%E9%AA%8C%E5%AE%A4%E4%BF%A1%E6%81%AF%E6%9F%A5%E8%AF%A2"
    print(f"正在访问URL: {url}")
    driver.get(url)

    print("\n浏览器已打开,请您手动完成以下操作:")
    print("1. 在浏览器中输入搜索内容")
    print("2. 提交查询")
    print("3. 点击查询结果中的链接,打开弹出网页")
    print("\n脚本将持续监控新窗口的出现...")

    # 持续监控窗口变化
    while True:
        # 获取当前所有窗口句柄
        current_windows = driver.window_handles

        # 如果发现新窗口
        if len(current_windows) > 1:
            # 找到新窗口
            new_window = None
            for window in current_windows:
                if window != original_window:
                    new_window = window
                    break

            if new_window:
                print(f"\n发现新窗口,正在保存内容...")
                # 保存新窗口内容
                save_to_excel(driver, new_window)

                # 关闭新窗口
                driver.close()
                # 切换回原始窗口
                driver.switch_to.window(original_window)

                # 询问是否继续监控
                print("\n是否继续监控新窗口?(y/n): ")
                choice = input().strip().lower()
                if choice != 'y':
                    break

        # 每2秒检查一次
        time.sleep(2)

    print("\n程序执行完成!")

except Exception as e:
    print(f"\n发生错误: {e}")
finally:
    # 关闭浏览器
    input("\n按回车键关闭浏览器并退出...")
    driver.quit()
    print("浏览器已关闭")

if name == "main ":

main()

相关推荐
坐公交也用券8 小时前
适用于vue3+pnpm项目自动化类型检查及构建的Python脚本
开发语言·javascript·python·typescript·自动化
serve the people8 小时前
tensorflow 深度解析 Sequential 模型的创建与层管理
人工智能·python·tensorflow
wfeqhfxz25887828 小时前
条形码识别与定位:基于FCOS框架的多类型条码检测与识别技术详解
python
free-elcmacom8 小时前
Python实战项目<3>赛制分数分析
开发语言·前端·python·数据分析
赵谨言8 小时前
基于OpenCV的数字识别系统
大数据·开发语言·经验分享·python
飞天小蜈蚣9 小时前
http协议和django初识
python
路边草随风9 小时前
langchain agent动态变更系统prompt
人工智能·python·langchain·prompt
哥本哈士奇(aspnetx)16 小时前
Streamlit + LangChain 1.0 简单实现智能问答前后端
python·大模型
我一定会有钱16 小时前
斐波纳契数列、end关键字
python