Selenium菜鸟教程学习笔记
本博客仅为个人学习记录与理解分享,非商业用途,所有代码与文档版权归原项目及其贡献者所有。selenium菜鸟教程
一、Selenium环境搭建
1.安装Selenium库
使用Python编写自动化脚本来控制浏览器
pipinstallselenium2.测试安装是否成功
运行demo1.py,观察到浏览器弹出又关闭,说明Selenium环境安装成功。
fromseleniumimportwebdriver driver=webdriver.Chrome()# 启动driver.get("https://www.bing.com/")# 控制driver.quit()# 关闭二、WebDriver的基本使用
可以看到edge弹出菜鸟网页并跳转到百度页面,再返回菜鸟页面并刷新,最终关闭浏览器的效果。
# 导入所需模块fromseleniumimportwebdriverfromselenium.webdriver.edge.serviceimportServiceasEdgeServicefromselenium.webdriver.edge.optionsimportOptionsasEdgeOptions# 自动管理 Edge 驱动(无需指定路径!)# Selenium 4+ 会自动下载并使用与你当前 Edge 版本匹配的驱动driver=webdriver.Edge()# 打开网页driver.get("https://www.runoob.com")# 最大化窗口driver.maximize_window()# 获取页面标题和 URLprint("页面标题:",driver.title)print("当前 URL:",driver.current_url)# 导航到另一个页面driver.get("https://www.jyshare.com")# 返回上一个页面driver.back()# 刷新页面driver.refresh()# 关闭浏览器driver.quit()三、常见元素定位方式测试
1.创建本地 HTML 测试页面
目的:验证 By.ID、By.NAME、By.CSS_SELECTOR、By.XPATH 四种定位方式
(命名为test_login.html,该 .html 文件与 .py 脚本置于同一目录)
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Test Login Page</title></head><body><form><inputtype="text"id="username"placeholder="Enter username"><br><br><inputtype="password"name="password"placeholder="Enter password"><br><br><buttontype="button"class="submit-btn">Submit</button><br><br><ahref="https://www.baidu.com"target="_blank">Click Here</a></form><script>// 可选:给按钮加点击事件,避免页面跳转中断脚本document.querySelector('.submit-btn').addEventListener('click',()=>{// alert('Form submitted!');console.log('Form submitted!');});</script></body></html>2.Python 脚本验证定位效果
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByimportos driver=webdriver.Edge()# 与实际使用的浏览器一致html_file=os.path.abspath("test_login.html")driver.get(f"file://{html_file}")# ID 定位driver.find_element(By.ID,"username").send_keys("testuser")# Name 定位driver.find_element(By.NAME,"password").send_keys("password123")# CSS 定位driver.find_element(By.CSS_SELECTOR,"button.submit-btn").click()# XPath 定位driver.find_element(By.XPATH,"//a[text()='Click Here']").click()print("✅ 定位与操作完成!请按 F12 检查页面(注意:百度在新标签页打开)")input("🔍 检查完毕后按回车退出...")driver.quit()3.运行结果
- 用户名、密码成功输入
- 提交按钮点击后控制台输出日志
- “Click Here” 链接在新标签页中打开百度
- input保持原始页面打开,便于调试
四、等待机制
1.隐式等待(全局)
一旦设置,对所有后续的 find_element(s) 调用生效。
- 优点:简单,一行代码全局生效。
- 缺点:
所有元素共用同一个超时时间,缺乏灵活性;
与显式等待混用时会产生不可预测的等待时间叠加(这是最严重的问题!)。
2.显示等待(局部)
为不同的查找设置不同的等待时间,是 Selenium 官方推荐的做法。比如:用户名输入框,应该很快出现(1 ~ 2秒内)。如果 3 秒还没出来,说明页面加载失败。登录成功后的欢迎消息:需要调用后端 API,可能要8~10 秒才出现。
具体写法如下所示:
fromseleniumimportwebdriverfromselenium.webdriver.chrome.serviceimportServiceasChromeServicefromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasECimportos# 设置正确的驱动路径driver=webdriver.Edge()# 设置隐式等待# driver.implicitly_wait(5) # 最好不要使用# 打开网页html_file=os.path.abspath("test_login.html")driver.get(f"file://{html_file}")# 使用显式等待等待元素可见username=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID,"username")))username.send_keys("testuser")# 使用显式等待等待元素可点击submit_button=WebDriverWait(driver,15).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button.submit-btn")))submit_button.click()# 关闭浏览器driver.quit()五、文件上传和下载
1.创建本地测试页面
命名为test_page.html,保存在.py文件夹下
<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="UTF-8"><title>Selenium 文件操作测试页</title><style>body{font-family:sans-serif;padding:20px;}.section{margin-bottom:30px;padding:15px;border:1px solid #ddd;border-radius:5px;}h2{margin-top:0;color:#333;}button{padding:10px 20px;cursor:pointer;background:#007bff;color:white;border:none;border-radius:3px;}button:hover{background:#0056b3;}</style></head><body><!-- 1. 上传测试区域 --><divclass="section"><h2>📤 文件上传测试</h2><p>请选择一个本地文件(模拟上传):</p><inputtype="file"id="fileInput"><buttononclick="alert('文件路径已获取,模拟上传成功!')">提交上传</button></div><!-- 2. 下载测试区域 --><divclass="section"><h2>⬇️ 文件下载测试</h2><p>点击下载按钮,浏览器将生成并下载一个文本文件:</p><buttonid="downloadBtn">点击下载测试文件</button></div><script>// 模拟下载逻辑:创建一个 Blob 文件并触发下载document.getElementById('downloadBtn').addEventListener('click',function(){constcontent="这是 Selenium 自动下载生成的测试内容\n时间:"+newDate().toLocaleString();constblob=newBlob([content],{type:'text/plain'});consturl=URL.createObjectURL(blob);consta=document.createElement('a');a.href=url;a.download='selenium_auto_download.txt';// 下载的文件名document.body.appendChild(a);a.click();// 清理资源document.body.removeChild(a);URL.revokeObjectURL(url);});</script></body></html>2.Python 脚本测试上传、下载效果
importosimporttimefromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# 1. 准备工作:创建下载目录download_dir=os.path.join(os.getcwd(),"downloads")os.makedirs(download_dir,exist_ok=True)# 2. 配置浏览器:核心是设置下载路径,禁止弹窗options=webdriver.EdgeOptions()options.add_experimental_option("prefs",{"download.default_directory":download_dir,"download.prompt_for_download":False})# 启动浏览器driver=webdriver.Edge(options=options)# 3. 打开本地测试页面 (确保 test_page.html 和这个脚本在一起)html_path="file:///"+os.path.abspath("test_page.html")driver.get(html_path)# --- 核心操作:上传 ---print("正在上传...")# 找到 input 标签,直接发送文件路径# 这里我们临时创建一个文件用来上传test_file=os.path.join(download_dir,"upload_test.txt")withopen(test_file,"w")asf:f.write("测试内容")upload_input=driver.find_element(By.ID,"fileInput")upload_input.send_keys(test_file)# <--- 核心就这一行print("上传完成")# --- 核心操作:下载 ---print("正在下载...")# 点击下载按钮download_btn=driver.find_element(By.ID,"downloadBtn")download_btn.click()# 结束input("下载完成")driver.quit()3.运行结果
上传:找到 标签,用 send_keys 发送文件的“绝对路径”。
下载:启动浏览器时加 options 配置(禁止弹窗 + 指定路径),然后点击网页上的下载链接。
六、Selenium测试框架集成
1. 与 unittest 集成
- 准备 (setUp):每次测试前都要做的事(如:打开浏览器、打开网页);
- 执行 (test_):具体的测试步骤(如:输入文字、点击按钮);
(注意:函数名必须以 test 开头,否则不执行。) - 收尾 (tearDown):每次测试后都要做的事(如:关闭浏览器)。
importunittestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasECclassTestGoogleSearch(unittest.TestCase):defsetUp(self):self.driver=webdriver.Edge()self.driver.get("https://www.baidu.com")deftest_search(self):search_box=self.driver.find_element(By.NAME,"wd")search_box.send_keys("Selenium")search_box.submit()# 断言结果页标题包含"Selenium"self.assertIn("Selenium",self.driver.title)deftearDown(self):# 关闭浏览器self.driver.quit()if__name__=="__main__":unittest.main()2.与 pytest 集成
1.像写脚本。直接写函数就行,不用套在 class 里。
2.用 @pytest.fixture 装饰器,灵活控制。你可以让 10 个测试共用一个浏览器,也可以让每个测试单独用一个。
3.直接用 Python 原生的 assert 关键字就行。
4.需要 yield driver 来传递浏览器。
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# 这个 scope="session" 的意思是:整个测试过程只启动一次浏览器@pytest.fixture(scope="session")defbrowser():driver=webdriver.Edge()yielddriver# 先跑测试用例driver.quit()# 所有测试跑完后才执行这一句# 测试用例写法保持不变deftest_baidu_search(browser):browser.get("https://www.baidu.com")search_box=browser.find_element(By.NAME,"wd")search_box.send_keys("Selenium")search_box.submit()assert"Selenium"inbrowser.title