UI自动化测试--webdriver驱动浏览器
今天来谈一下使用Webdriver+selenium 框架来实现PC端UI自动化,关于UI自动化,目前在他的效果,成本等方面都存在很多争议,尽管他有很多的缺点,但是合理利用之下,还是能帮助我们解放一定的劳动力的。
本篇不在于讨论其优缺点,所以我们直接展示方法。前期我们需要做一些准准备工作
1. 下载驱动
https://www.selenium.dev/downloads/
可以看到,selenium支持大部分常用的浏览器,我们以Chrome浏览器为例,下载驱动chromedriver.exe
还可以下载Android或IOS驱动,用来实现手机wap端的UI自动化
2. 在pom.xml中配置相关jar包依赖
<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-chrome-driver</artifactId><version>3.141.59</version></dependency>
3. 加载驱动,设置浏览器属性
ChromeDriver是Chromium team开发维护的,它是实现WebDriver有线协议的一个单独的服务。ChromeDriver通过chrome的自动代理框架控制浏览器
public class chromeDriver{System.setProperty("webdriver.chrome.driver","webdriver.path");// 创建一个新的ChromeDriver的实例Webdriver webdriver = new ChromeDriver();// 设置打开的浏览器窗口最大化webdriver.manage().window().maximize();// 使用get()打开一个网站webdriver.get("https://www.baidu.com/");webdriver.quit();}}}
4. 通过设置属性来实现,在PC端模拟wap浏览器
public WebDriver chromeDriverForWap() {//设置webdriver.chrome.driver属性System.setProperty("webdriver.chrome.driver", "webdriver.path");//声明ChromeOptions,主要是给chrome设置参数ChromeOptions options = new ChromeOptions();//设置user agent为iphone6plusoptions.addArguments("--user-agent=iphone 6 plus");options.addArguments("lang_zh_CN.UTF-8");//这步是关键哦,指定的浏览器size,对应手机型号的sizeoptions.addArguments("window-size=375,667");options.addArguments("user-agent=\"Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0 Mobile/15C114 Safari/604.1\"");WebDriver driver = new ChromeDriver(options);driver.get("https://m.baidu.com/");driver.quit();}
