Selenium 自动访问网站并提取信息保存到 Excel 教程

你希望通过 Selenium 自动访问网站,提取网址、网站名称、description、keywords 并保存到 Excel,我会为你提供完整的实现方案,包括代码和详细说明。

7498f52938a36474a153ba7fadfeb920

一、前置准备:安装必要库

首先需要安装两个核心库,打开命令行执行以下命令:
# 安装 Selenium(浏览器自动化工具)
pip install selenium
# 安装 openpyxl(操作 Excel xlsx 格式文件的库,支持读写)
pip install openpyxl
说明:Selenium 4.6.0 及以上版本无需手动下载浏览器驱动(ChromeDriver/GeckoDriver),会自动管理驱动,推荐使用高版本 Selenium。

二、完整实现代码

python

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from openpyxl import Workbook
import time

def get_website_info(target_urls, excel_save_path="website_info.xlsx"):
    # 1. 初始化 Excel 工作簿和工作表
    wb = Workbook()
    ws = wb.active
    ws.title = "网站信息汇总"
    # 设置 Excel 表头
    headers = ["网站网址", "网站名称(title)", "网站描述(description)", "网站关键词(keywords)"]
    ws.append(headers)

    # 2. 初始化 Selenium 浏览器(Chrome)
    # 可选配置:无头模式(不弹出浏览器窗口)
    chrome_options = webdriver.ChromeOptions()
    # 注释下面这行可以显示浏览器窗口,方便调试
    chrome_options.add_argument("--headless=new")
    driver = webdriver.Chrome(options=chrome_options)

    try:
        # 3. 遍历目标网址,逐个提取信息
        for url in target_urls:
            website_info = []
            try:
                # 访问目标网站
                driver.get(url)
                # 等待页面加载(可选,根据网站情况调整时间)
                time.sleep(2)

                # 提取 1:网站网址(当前页面的 URL)
                current_url = driver.current_url
                website_info.append(current_url)
                print(f"正在处理网址:{current_url}")

                # 提取 2:网站名称(title 标签内容)
                try:
                    title = driver.title
                    website_info.append(title)
                except Exception:
                    website_info.append("未获取到网站名称")

                # 提取 3:网站 description(meta 标签 name="description" 的 content 属性)
                try:
                    description_meta = driver.find_element(
                        By.XPATH, '//meta[@name="description"]'
                    )
                    description = description_meta.get_attribute("content")
                    website_info.append(description.strip() if description else "无描述")
                except NoSuchElementException:
                    website_info.append("未找到 description 标签")
                except Exception:
                    website_info.append("获取 description 失败")

                # 提取 4:网站 keywords(meta 标签 name="keywords" 的 content 属性)
                try:
                    keywords_meta = driver.find_element(
                        By.XPATH, '//meta[@name="keywords"]'
                    )
                    keywords = keywords_meta.get_attribute("content")
                    website_info.append(keywords.strip() if keywords else "无关键词")
                except NoSuchElementException:
                    website_info.append("未找到 keywords 标签")
                except Exception:
                    website_info.append("获取 keywords 失败")

                # 将当前网站信息写入 Excel 工作表
                ws.append(website_info)

            except WebDriverException as e:
                print(f"访问网址 {url} 失败:{str(e)}")
                # 访问失败时,填充异常信息
                error_info = [url, "访问失败", "访问失败", "访问失败"]
                ws.append(error_info)
            except Exception as e:
                print(f"处理网址 {url} 出现未知错误:{str(e)}")
                error_info = [url, "未知错误", "未知错误", "未知错误"]
                ws.append(error_info)

        # 4. 保存 Excel 文件
        wb.save(excel_save_path)
        print(f"\n所有网站信息已保存到:{excel_save_path}")

    finally:
        # 5. 关闭浏览器,释放资源
        driver.quit()
        wb.close()

if __name__ == "__main__":
    # 自定义目标网站列表(可修改为你需要的网址)
    target_website_list = [
        "https://www.baidu.com",
        "https://www.zhihu.com",
        "https://www.csdn.net"
    ]
    # 调用函数,指定 Excel 保存路径(默认当前目录)
    get_website_info(
        target_urls=target_website_list,
        excel_save_path="我的网站信息汇总.xlsx"
    )

三、关键功能说明

1. 信息提取逻辑

信息项提取方式
网站网址driver.current_url:获取浏览器当前加载页面的完整 URL
网站名称driver.title:直接获取 HTML 中 <title> 标签的文本内容
descriptionXPATH 定位 //meta[@name="description"],再通过 get_attribute("content") 获取属性值
keywordsXPATH 定位 //meta[@name="keywords"],再通过 get_attribute("content") 获取属性值

2. 核心特性

  • 异常处理:捕获网站访问失败、标签不存在等异常,避免程序中断,同时填充提示信息
  • 无头模式:默认不弹出浏览器窗口(注释对应代码可显示窗口调试)
  • 批量处理:支持传入多个网址,自动遍历提取信息
  • Excel 格式化:自动设置表头,按行写入每个网站的信息

3. 使用方法

  1. 修改 target_website_list 为你需要访问的网站网址列表
  2. 可选修改 excel_save_path 自定义 Excel 保存路径和文件名
  3. 运行代码,等待执行完成后,在指定路径找到 Excel 文件
  4. 若需要显示浏览器窗口,注释 chrome_options.add_argument("--headless=new") 即可

四、常见问题解决

  1. 浏览器启动失败:确保已安装 Chrome 浏览器,若使用 Edge/Firefox,替换 webdriver.Chrome 为 webdriver.Edge/webdriver.Firefox 即可
  2. 标签未找到:部分网站的 meta 标签可能使用 property 而非 name(如 property="og:description"),可修改 XPATH 表达式适配
  3. 页面加载不完整:增加 time.sleep() 时间,或使用 WebDriverWait 显式等待(更优雅的等待方式)
  4. Excel 无法打开:确保程序正常执行完毕(浏览器已关闭),避免文件被占用

总结

  1. 核心依赖:selenium(自动化访问)+ openpyxl(Excel 操作),需提前安装
  2. 信息提取:通过 current_urltitle 和 XPATH 定位 meta 标签实现
  3. 关键步骤:初始化浏览器 → 遍历网址 → 提取信息 → 写入 Excel → 释放资源
  4. 灵活配置:支持批量网址、自定义保存路径、无头 / 可视化模式切换

广告也精彩
 
老罗爱折腾
  • 本文由 老罗爱折腾 发表于2025 年 12 月 29 日 13:42:34
  • 转载请务必保留本文链接:https://www.130510.com/1804.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证