浏览器配置 + 文件上传 + 截图

Selenium 进阶内容:浏览器配置 + 文件上传 + 截图

一、浏览器配置(EdgeOptions)

作用:自定义浏览器启动参数,常用场景:无头运行(无界面跑脚本,服务器执行)、禁止弹窗、忽略证书报错、禁用GPU、设置窗口大小等。

导入

python 复制代码
from selenium.webdriver.edge.options import Options

常用参数说明

参数 作用
--headless=new 无头模式:不弹出浏览器窗口,后台运行
--disable-gpu 禁用GPU渲染(部分windows环境无头必备)
--ignore-certificate-errors 忽略https证书报错
--start-maximized 启动直接最大化窗口
--disable-notifications 禁止网页弹窗通知

完整示例(无头模式)

python 复制代码
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options

# 实例配置对象
edge_options = Options()
# 开启无头模式
edge_options.add_argument("--headless=new")
edge_options.add_argument("--disable-gpu")
edge_options.add_argument("--ignore-certificate-errors")

web_driver = webdriver.Edge(
    service=Service(r"D:\Software\edgedriver_win64\msedgedriver.exe"),
    options=edge_options
)
web_driver.get("https://www.baidu.com")
print(web_driver.title)
web_driver.quit()

⚠️ 重点:本地调试不要开无头;服务器部署自动化脚本使用无头

二、文件上传

场景区分

  1. input标签 type="file" ✅ Selenium原生支持(最常见)
    原理:定位上传输入框,直接 send_keys(文件绝对路径),不需要模拟点击弹窗选文件!
  2. 非input、自定义上传弹窗(Windows资源管理器弹窗)❌ selenium无法处理,需要第三方库如pyautogui

标准示例

python 复制代码
# 定位上传输入框
upload_ele = wait.until(EC.visibility_of_element_located((By.XPATH, '//input[@type="file"]')))
# 传入本地文件【绝对路径】
upload_ele.send_keys(r"D:\test.jpg")

三、截图操作

两种截图方式

  1. 截取整个浏览器页面 :driver.save_screenshot("图片保存路径.png")
  2. 截取单个元素 :element.screenshot("图片路径.png")
python 复制代码
# 页面截图
web_driver.save_screenshot(r"D:\page.png")

# 元素截图
search_input = wait.until(EC.visibility_of_element_located((By.ID, "kw")))
search_input.screenshot(r"D:\input.png")

注意:路径尽量使用原始字符串 r"";保存目录必须存在,否则报错


✅ 综合课堂练习

需求:

  1. 配置Edge,忽略证书报错,启动自动最大化
  2. 打开百度首页
  3. 页面截图保存到本地
  4. 在搜索框输入 自动化测试
  5. 点击搜索
  6. 关闭浏览器
相关推荐
我命由我123452 分钟前
Python 开发 - Python 项目部署(Windows 与 Linux)
java·linux·windows·后端·python·java-ee·python3.11
Zella折耳根18 分钟前
实验2进阶版数据看板的设计与实现
python
databook26 分钟前
让 LLM 输出不再失控:用 Pydantic 校验大模型输出
人工智能·python·llm
jingcairensheng28 分钟前
vscode 配置Python虚拟环境基于扩展和原生miniconda的区别
ide·vscode·python
“AI国潮设计-小江”37 分钟前
《【AIGC实战】Python+SDXL批量生成“英歌舞草莓抱抱卷蛋糕”IP插牌立牌方案,锁定角色一致性,甜品插件化落地》
开发语言·人工智能·python·prompt·aigc
LMT流氓兔37 分钟前
第五单元——第7课:工具读取用户身份,而不是让模型填写身份
python·langchain
FlyWIHTSKY41 分钟前
Agent阶段一:基础夯实
python·ai·fastapi
估值探索者42 分钟前
【Python量化技术指标实战 04】布林带通道突破,怎么知道是真突破还是假突破?
java·开发语言·python·接口·股票数据api接口
fanruitian1 小时前
python property
开发语言·python
Web3&Basketball1 小时前
MiniMax M3.1 Flash实战:3个成本坑
python·大模型·成本优化·minimax·推理优化·token计费