因为我使用的是Chrome浏览器,所以需要下载chromedrive.exe,附上下载链接http://chromedriver.storage.googleapis.com/index.html,
为了便于管理,将其放在了lib库下面。
有了驱动,下面就开始去执行打开动作了
一、PC端
try{ System.setProperty("webdriver.chrome.driver", "D:\\Program Files\\eclipse\\workspace\\AutoTestForWEB\\lib\\chromedriver.exe"); }catch(NullPointerException e){ throw new Exception("没有找到驱动文件!"); } // 初始化驱动,即打开浏览器 webdriver = new ChromeDriver(); // 设置打开的浏览器窗口最大化getSize():获取窗口的大小 System.out.println("窗口大小:"+webdriver.manage().window().getSize()); webdriver.manage().window().maximize(); System.out.println("窗口大小:"+webdriver.manage().window().getSize()); // 设置隐性的等待时间,等待页面全部元素加载完成,5秒之内没有全部加载报超时异常 // webdriver.implicitly_wait(10); System.out.println("隐式等待页面加载时间戳1:"+System.currentTimeMillis()); try{ webdriver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS); }catch(TimeoutException e){ throw new TimeoutException("页面加载超时"); } // 使用get()打开一个网站 webdriver.get("www.baidu.com");
使用JVM自带的setProperty()方法来加载驱动,selenium提供了WebDriver接口来调用驱动,其中maximize()让浏览器窗口最大化,get()方法指定要访问的网站,比如get("www.baidu.com")
二、浏览器模拟wap端
值得一提的是如果想用浏览器模拟wap端,只要指定参数即可
/** * 关于Chrome浏览器启动参数,我们测试中常用的大概还有: * --disable-images(控制是否加载图片) * --start-maximized (启动时最大化) * download.default_directory": download_dir (设置下载保存路径) */ // 设置user agent为iphone6plus options.addArguments("--user-agent=iphone 6 plus");
//设置编码格式 options.addArguments("lang_zh_CN.UTF-8"); // 指定的浏览器size,对应手机型号的size options.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.chrome.driver属性
ChromeOptions的addArguments()方法指定浏览器属性,我指定了 iphone 6 plus,实际上就是完成了操作