Selenium 自动化实战技巧【selenium】

🧰 更多 Selenium 自动化操作技巧

1️⃣ 鼠标交互操作(ActionChains)

Selenium 提供 ActionChains 类来模拟用户的复杂鼠标行为,如:

  • 移动光标到某元素上(悬浮触发事件)
  • 鼠标右键、双击
  • 拖拽元素等

📌 示例:模拟将鼠标移动到百度首页的"更多产品"菜单上:

复制代码
from selenium.webdriver.common.action_chains import ActionChains

ac = ActionChains(driver)
target = driver.find_element(By.CSS_SELECTOR, '[name="tj_briicon"]')
ac.move_to_element(target).perform()

2️⃣ 执行 JavaScript 脚本

Selenium 支持直接执行 JS 脚本,用于获取 DOM 属性或处理页面行为。

示例:检查分页按钮是否可用
复制代码
disabled = driver.execute_script('''
    let ele = document.querySelector('.soupager > button:last-of-type');
    return ele.getAttribute('disabled');
''')

if disabled == 'disabled':
    return True
将元素滚动到视口中(避免点击失败)
复制代码
driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})", element)

3️⃣ 冻结页面以辅助调试

某些浮动菜单或弹窗,在鼠标移出时会立即消失,不方便抓取元素信息。可在浏览器开发者工具的控制台执行:

复制代码
setTimeout(function(){debugger}, 5000)

在 5 秒内将鼠标悬停目标区域,随后浏览器将冻结当前界面,便于检查 HTML 结构。


4️⃣ 处理弹窗(Alert、Confirm、Prompt)

Selenium 提供 switch_to.alert 接口操作 JS 弹窗:

Alert 弹窗(只包含提示信息)
复制代码
driver.switch_to.alert.text  # 获取内容
driver.switch_to.alert.accept()  # 点击确认
Confirm 弹窗(确认/取消选择)
复制代码
driver.switch_to.alert.accept()   # 确认
driver.switch_to.alert.dismiss()  # 取消
Prompt 弹窗(输入内容)
复制代码
alert = driver.switch_to.alert
alert.send_keys("selenium自动化")
alert.accept()

❗提示:非 JS 弹窗(HTML 构建)需用正常元素选择器处理。


5️⃣ 控制窗口与页面信息

获取或设置浏览器窗口参数:

  • driver.get_window_size():获取尺寸

  • driver.set_window_size(w, h):设置大小

  • driver.title:页面标题

  • driver.current_url:当前地址栏内容

    print(driver.title)
    print(driver.current_url)


6️⃣ 页面截图

使用 get_screenshot_as_file() 保存当前界面截图:

复制代码
driver.get_screenshot_as_file('screenshot.png')

7️⃣ 模拟手机设备

通过 ChromeOptions 配置移动设备环境,模拟手机访问网页:

复制代码
from selenium import webdriver

mobile_emulation = {"deviceName": "iPhone 14 Pro Max"}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(options=chrome_options)
driver.get('https://www.baidu.com')

8️⃣ 文件上传(支持多文件)

上传控件一般是 <input type="file">,只需通过 send_keys 指定文件路径:

复制代码
ele = wd.find_element(By.CSS_SELECTOR, 'input[type="file"]')
ele.send_keys(r'h:\test.png')

📂 多文件上传(支持多次调用):

复制代码
ele.send_keys(r'h:\img1.png')
ele.send_keys(r'h:\img2.png')

📌 如果上传控件不是标准的 file input,而是弹出系统窗口,可以借助 Windows 平台的 pywin32 库发送文件路径和回车:

复制代码
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Sendkeys(r"h:\img.png" + '\n')

9️⃣ 自动化 Edge 浏览器

Edge(基于 Chromium)需要下载对应版本的驱动,初始化方式如下:

复制代码
from selenium import webdriver

driver = webdriver.Edge(executable_path=r'd:\tools\webdrivers\msedgedriver.exe')
driver.get('https://www.51job.com')

这就是 Selenium 在常见交互行为、弹窗处理、浏览器控制、上传文件、移动端模拟等方面的进阶用法整理。

相关推荐
体系结构论文研讨会4 分钟前
多项式环及Rq的含义
算法
智驱力人工智能13 分钟前
极端高温下的智慧出行:危险检测与救援
人工智能·算法·安全·行为识别·智能巡航·高温预警·高温监测
森焱森21 分钟前
60 美元玩转 Li-Fi —— 开源 OpenVLC 平台入门(附 BeagleBone Black 驱动简单解析)
c语言·单片机·算法·架构·开源
课堂剪切板1 小时前
ch07 题解
算法·深度优先
科大饭桶3 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
测试开发技术4 小时前
如何在 Pytest 中调用其他用例返回的接口参数?
面试·自动化·pytest·接口·接口测试·api测试
我爱C编程5 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法
chao_7895 小时前
CSS表达式——下篇【selenium】
css·python·selenium·算法
随便写个昵称5 小时前
selenium跳转到新页面时如何进行定位
selenium·测试工具
随便写个昵称5 小时前
登录为图片验证时,selenium通过token直接进入页面操作
selenium·测试工具