项目:测试百度搜索关键词后,跳转页面标题的正确性 运行环境:win10系统
selenium web driverpython3pytest配置文件:iselenium.ini
将配置文件复制到本地磁盘的[user.home]目录填入设备的chromwebdriver文件的全路径[user.home]目录: mac系统命令: cd ~ Windows系统:C://Users/{用户名}
web_ut.py代码:
import configparser import os import time import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options class ISelenium(unittest.TestCase): # 读入配置文件 def get_config(self): config = configparser.ConfigParser() config.read(os.path.join(os.environ['HOME'], 'iselenium.ini')) return config def setUp(self): config = self.get_config() # 控制是否采用无界面形式运行自动化测试 try: using_headless = os.environ["using_headless"] except KeyError: using_headless = None print('没有配置环境变量 using_headless, 按照有界面方式运行自动化测试') chrome_options = Options() if using_headless is not None and using_headless.lower() == 'true': print('使用无界面方式运行') chrome_options.add_argument("--headless") self.driver = webdriver.Chrome(executable_path=config.get('driver', 'chrome_driver'), options=chrome_options) def tearDown(self): self.driver.quit() def test_webui_1(self): """ 测试用例1,验证'今日头条'关键词在百度上的搜索结果 """ self._test_baidu('今日头条', 'test_webui_1') def test_webui_2(self): """ 测试用例2, 验证'王者荣耀'关键词在百度上的搜索结果 """ self._test_baidu('王者荣耀', 'test_webui_2') def _test_baidu(self, search_keyword, testcase_name): """ 测试百度搜索子函数 :param search_keyword: 搜索关键词 (str) :param testcase_name: 测试用例名 (str) """ self.driver.get("https://ww.baidu.com") print('打开浏览器,访问 www.baidu.com') time.sleep(5) assert f'百度一下' in self.driver.title elem = self.driver.find_element_by_name("wd") elem.send_keys(f'{search_keyword}{Keys.RETURN}') print(f'搜索关键词~{search_keyword}') time.sleep(5) self.assertTrue(f'{search_keyword}' in self.driver.title, msg=f'{testcase_name}校验点 pass')iselenium.ini文件:
错误1 keyerror对应路径有误
设置好iselenium.ini,并放置在C://Users/mai下,运行web_ut.py文件报错:
D:\Program Files (x86)\python\python37\lib\os.py:681: KeyError
解决1: 已提示KeyError: ‘HOME’,百度windows系统[user.home]目录参数是’HOMEPATH‘,修改后再次运行报错:
D:\Program Files (x86)\python\python37\lib\configparser.py:1146:NoSectionError
解决2: 1)百度该错误,是配置文件路径有误,找不到该配置文件;
2)找到了配置文件但是读取有问题,No section: ‘driver’。(我猜的)
先看1),图省事的直接config.read()输入配置文件的绝对路径,想折腾的看os.environ[’HOMEPATH‘]到底传了个什么路径
os.environ.keys()可知,[‘HOMEPATH’]对应的路径1少了C:,正确路径应该是:[‘USERPROFILE’]对应的路径2。
错误2: 找不到目录’Google Chrome
WebDriverException: Message: ‘‘Google Chrome’’ executable needs to be in PATH
我写的iselenium.ini…不要问为什么加’ '因为中间有空格…总之是自作聪明,没有 ’ ‘!!
错误3: 目录Google Chrome,执行文件可能具有错误的权限
WebDriverException: Message: ‘Google Chrome’ executable may have wrong permissions.
总之经过百度改权限一番折腾什么的就不叙述了…突然想起来appium自动化,其中的chromedriver就是要指定具体的执行文件如下 下面也可以,总之运行起来了,完事收工!
[driver] chrome_driver=D:\Program Files (x86)\Google Chrome\chromedriver