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

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. 关闭浏览器
相关推荐
Fluxproxy2 小时前
Python请求玄学根治:彻底解决脚本间歇性超时、断连、假死问题
网络·python·安全
青 春 记 忆2 小时前
零基础入门Python15|关联、聚合、索引与事务:订单数据库
开发语言·python·后端开发
TELL5213 小时前
启动后端服务跑第一个用例成功,重新跑第二个用例chromedriver死活不成功,猜测是chromedriver本身的问题
selenium·webdriver
qq_513728043 小时前
Alert 原生弹窗处理
python
李可以量化3 小时前
Redis 从了解到精通(三)上:量化交易场景下的数据备份与安全配置
redis·python·安全·qmt·ptrade
卷无止境3 小时前
FastAPI查询参数模型:把散落的参数收拢成一个整齐的盒子
后端·python
Code额4 小时前
Python asyncio 异步编程全套学习文档(零基础完整版)
python·学习·oracle·async·异步·asyncio
钱栈up4 小时前
Mac 开发机一键发版不用切环境:我这样改造了团队的后端部署脚本
运维·python·mac