目录
一、简介
Selenium是一个功能强大、灵活性高的Web自动化测试工具,具有以下特点:
- 开源、免费
- 支持多种浏览器:Chrome、Firefox、Safari、Edge等
- 支持多种平台:Windows、Linux、MacOS
- 支持多种编程语言:Python、Java、C#等
- 支持多种测试框架:JUnit、unittest、Pytest等
- 支持多种Web元素定位:ID、Name、Class、CSS等
- 支持JavaScript脚本:可以执行JavaScript脚本
- 支持多线程:可以同时控制多个浏览器
参考资料:
官方网站:https://www.selenium.dev/
官方文档:https://www.selenium.dev/documentation/
二、安装
首先需要安装Python第三方库Selenium,安装比较简单,使用pip安装即可。
pip install selenium
其次,Selenium需要浏览器驱动程序来控制浏览器,不同浏览器需要不同的驱动程序。以下是常见浏览器的驱动程序下载地址:
Chrome:https://chromedriver.chromium.org/downloads
Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox:https://github.com/mozilla/geckodriver/releases
Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/
三、入门
首先创建test.py文件,然后将前面下载好的驱动放到同一目录下。
示例代码:
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
class BaiduTest(unittest.TestCase):
"""Selenium测试"""
# 打开浏览器
driver = webdriver.Chrome()
@classmethod
def setUpClass(cls) -> None:
# 打开百度
cls.driver.get('https://www.baidu.com/')
# 设置等待时间(隐式等待)
cls.driver.implicitly_wait(20)
@classmethod
def tearDownClass(cls) -> None:
# 退出浏览器
cls.driver.quit()
def test_page_title(self):
"""验证标题是否正确"""
# 断言
self.assertEqual(self.driver.title, '百度一下')
def test_search(self):
"""查找功能"""
# 输入查询内容
self.driver.find_element(By.ID, 'kw').send_keys('Selenium')
# 点击百度一下按钮
self.driver.find_element(By.ID, 'su').click()
time.sleep(10)
if __name__ == '__main__':
unittest.main()
在上面的例子中,我们实现了以下功能:
- 打开Chrome浏览器
- 打开百度网站(在setUpClass中实现的)
- 验证页面标题是否是“百度一下”
- 输入要查询的内容:Selenium
- 点击“百度一下”按钮
- 测试结束后关闭浏览器(在tearDownClass中实现)
用例编写完成以下,运行以下命令:
python test.py
测试完成之后,我们可以看到控制台输出如下内容:
因为页面的标题为“百度一下,你就知道”,与预期结果“百度一下”不一致,所以测试结果是不通过的(F),最后显示出执行了2条测试,其中1条是失败的。
以上就是使用Python+Selenium实现Web自动化测试的入门操作。
如有什么意见与建议,请在评论区留言吧!
如果你觉得文章对你有一点点帮助,烦请各位动动小手,点赞、关注、收藏!谢谢!