使用selenium实现UI自动化(一)
selenium,UI自动化测试的工具,包括webdriver,IDE,grid三个核心组件
安装selenium
pip install selenium
python下的使用步骤:
- 安装selenium
- 安装python
- 下载webdriver,并配置环境变量,以chromedriver为例子,在cmd输入chromedriver如果显示对应版本信息,代表设置成功
- 代码中import selenium
IDE
我们可以借助IDE的录制功能来加快我们的编写代码步骤,然后添加上自定义的操作,比如等待,然后导出python脚本。这里看个人喜好,具体使用这里自行百度
GRID
支持在多台不同的执行机上运行测试用例,在案例集比较庞大时,可以用来加快执行
如下是通过ide录制的简单例子,已经在本地设置过webdriver的环境变量
# Generated by Selenium IDE import pytest import time from selenium import webdriver from selenium.webdriver.common.by import By class TestSearch: def setup_method(self, method): self.driver = webdriver.Chrome() def teardown_method(self, method): self.driver.quit() def test_search(self): self.driver.get("https://www.baidu.com/") self.driver.find_element(By.ID, "kw").send_keys("时间") self.driver.find_element(By.ID, "su").click() time.sleep(3) self.driver.find_element(By.LINK_TEXT, "北京时间 - 国家授时中心标准时间").click()if __name__ == "__main__": pytest.main()
实际执行自动化脚本时,会出现由于执行太快而导致出现元素没有定位到从而导致报错的问题,为了避免这种,在上述例子中,我增加了简单的等待time.sleep
这种做法只能在调试中使用,切记不要在正式环境中使用,然后selenium提供了其他等待处理方式
隐式等待
self.driver.implicitly_wait(3)
将直接等待time.sleep(3)去掉,然后在setup中加入上述隐式等待,这样子就可以实现在元素找到后立刻执行下一步,如果没找到会在3秒后才会结束,缺点也有,就是这会作用于所有的find_element方法上,这样子不同的元素出现的时间不一致,那么等待的时间不好权衡。到这里,我们有另外一种等待方式,显示等待
WebDriver配合until()和until_not(),再结合内置的expected_conditions的方法使用
显式等待
将time.sleep(3)替换下,用显式等待替换,修改后如下
# Generated by Selenium IDE import pytest import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait class TestSearch: def setup_method(self, method): self.driver = webdriver.Chrome() def teardown_method(self, method): self.driver.quit() def test_search(self): self.driver.get("https://www.baidu.com/") self.driver.find_element(By.ID, "kw").send_keys("时间") WebDriverWait(self.driver, 10).until( expected_conditions.element_to_be_clickable((By.ID, "su"))) self.driver.find_element(By.ID, "su").click() WebDriverWait(self.driver, 10).until( expected_conditions.element_to_be_clickable((By.LINK_TEXT, "北京时间 - 国家授时中心标准时间"))) self.driver.find_element(By.LINK_TEXT, "北京时间 - 国家授时中心标准时间").click() if __name__ == "__main__": pytest.main()
到此,最简单的UI自动化就实现了
浙公网安备 33010602011771号