python使用selenium进行Web自动化测试
什么是selenium
Selenium 是 ThoughtWorks 提供的一个强大的基于浏览器的开源自动化测试工具。
Selenium 是一个用于 Web 应用程序测试的工具,测试直接自动运行在浏览器中,就像真正的用户在手工操作一样。支持的浏览器包括 IE、Chrome 和 Firefox 等。这个工具的主要功能包括:测试与浏览器的兼容性 - 测试您的应用程序看是否能够很好地工作在不同浏览器和操作系统之上;测试系统功能 - 创建回归测试检验软件功能和用户需求;支持自动录制动作,和自动生成 .NET、Perl、Python、Ruby 和 Java 等不同语言的测试脚本。
安装python
安装selenium
pip install selenium
检测selenium
pip show selenium
(venv) ➜ pytest pip show selenium
Name: selenium
Version: 4.1.0
Summary:
Home-page: https://www.selenium.dev
Author:
Author-email:
License: Apache 2.0
Location: /Users/terwer/Documents/PycharmProjects/pytest/venv/lib/python3.8/site-packages
Requires: trio, trio-websocket, urllib3
Required-by:
安装driver
firefox
下载geckdriver
下载地址:https://github.com/mozilla/geckodriver/releases ,需注意的是浏览器的版本和driver驱动的版本要匹配
Google chrome
(Chrome对应Chromedriver,ie对应IEdriver)
下载对应版本的压缩包,然后解压,解压后的名称都是一样的,driver的路径可以放在python的script的路径下
https://chromedriver.chromium.org/downloads
错误解决
'chromedriver' executable needs to be in PATH.
找到文档
https://chromedriver.chromium.org/getting-started
edge
https://docs.microsoft.com/zh-cn/microsoft-edge/webdriver-chromium/?tabs=python
python运行第一个自动化脚本
from selenium import webdriver
def print_hi(name):
driver = webdriver.Chrome("./chromedriver")
driver.get("https://www.baidu.com")
driver.quit()
print(f'Hi, {name}')
if __name__ == '__main__':
print_hi('Selenium')
解决自动退出
python+selenium自动化,没有写close和quit,浏览器窗口会自动关闭解决方案
加参数
option.add_experimental_option("detach", True)
完整的代码
# 加启动配置
option = webdriver.ChromeOptions()
# 关闭“chrome正受到自动测试软件的控制”
# V75以及以下版本
# option.add_argument('disable-infobars')
# V76以及以上版本
option.add_experimental_option('useAutomationExtension', False)
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# 不自动关闭浏览器
option.add_experimental_option("detach", True)
driver = webdriver.Chrome("./chromedriver", chrome_options=option)
driver.get("https://www.baidu.com")
driver.maximize_window()
# driver.quit()
edge版本
from msedge.selenium_tools import Edge, EdgeOptions
import os
def start_dege():
options = EdgeOptions()
options.binary_location = r'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'
options.use_chromium = True
options.set_capability("platform", "Mac OS")
# 不退出
options.add_experimental_option("detach", True)
browser = Edge(options=options, executable_path=r"/usr/local/bin/msedgedriver")
browser.get('http://localhost:8090')
def close_edge():
os.system("killall -9 'Microsoft Edge'")
print("previous Microsoft Edge is closed")
if __name__ == '__main__':
close_edge()
start_dege()
print("edge started")
全屏
option.add_argument("--start-maximized")
option.add_argument('window-size=2560,1440')