学习笔记(仅供参考)
起因:
在自学UI自动化时候,发现执行代码时,老是需要调起浏览器,再进行UI自动化测试。如果我把登录作为一条测试用例的话,再在后面添加一条需要登录后才可以开始的场景作为用例,单独去执行第二天测试用例时就需要手动去登录,执行第三条时亦要如此(可能是我代码编写的问题)
解决思路:
1、利用cookie/session保持登录(已放弃)
2、使用 Selenium 的远程 WebDriver 功能。(察觉可行)
解决流程:
- 确保在 macOS 上安装了 Chrome WebDriver,
安装步骤:省略
验证:在终端输入chromedriver --version。
(我的chromedriver 是放在usr/local/bin里的) - 在 macOS 上配置谷歌浏览器调试端口:
打开Chrome浏览器并输入以下地址:chrome://version/,检查Command Line列表中是否包含 --remote-debugging-port=<端口号> 的项。(若有:跳到代码步骤)
(没有则)在终端输入:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
(我使用的端口是9222) 此时会自动打开一个浏览器,输入chrome://version/去验证
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import unittest
from selenium.webdriver.chrome.service import Service
class Search(unittest.TestCase):
def setUp(self):
# 设置 Chrome WebDriver 的路径,/usr/local/bin/chromedriver是我chromedriver的路径
chromedriver_path = '/usr/local/bin/chromedriver'
# 启动一个现有的 Chrome 实例
options = webdriver.ChromeOptions()
options.debugger_address = "localhost:9222"
# 创建一个 Service 对象,指定 Chrome WebDriver 路径
service = Service(chromedriver_path)
# 使用 Service 对象和 options 创建 ChromeWebdriver 实例
self.driver = webdriver.Chrome(service=service, options=options)
#第一条测试用例:
def test_send(self):
driver = self.driver
print(driver.title)
# # 这里可以添加更多的操作和交互
#第二条测试用例:
def test_send(self):
driver = self.driver
print(driver.title)
# # 这里可以添加更多的操作和交互
# 关闭浏览器窗口(可选)
def tearDown(self):
self.driver.close()
if __name__ == '__main__':
unittest.main()
结果:
在已打开的页面登录后,再运行代码就可以直接在当前的页面执行自动化了