一、指定不同位置的chrome浏览器。
如果安装了两个谷歌浏览器,一个是在谷歌的c盘的默认路径,一个是在比如,D:\Program Files.
那么驱动会默认使用c盘的exe,如果指定到D盘的exe?有2步。
1、
String src="src/main/resources/chromedriver.exe"; //chromedriver目录,绝对/相对路径 System.setProperty("webdriver.chrome.driver",src); ChromeOptions options = new ChromeOptions(); String exePath = "D:\\Program Files\\chrome.exe"; File file = new File(exePath); options.setBinary(file); WebDriver driver = new ChromeDriver(options);2、在系统变量上加“D:\\Program Files\\chrome.exe”
二、定位不到元素可能是有iframe嵌套
driver.get("https://www.xxx.com/"); //主窗口切换到iframe,参数可以是id,name等 driver.switchTo().frame("loginFrame"); driver.findElement(By.id("name")).sendKeys("test"); driver.findElement(By.id("password")).sendKeys("pawd"); driver.findElement(By.id("sub")).sendKeys(Keys.ENTER); //从iframe切换回主窗口 driver.switchTo().defaultContent();
三、切换到新开的窗口
有些网站点击会新开窗口
for (String windowHandle : driver.getWindowHandles()) { if(!windowHandle.equals(driver.getWindowHandle())){ driver.switchTo().window(windowHandle); break; } }
四、有的网页input类型的checkBox太多,可以换用勾选它的父级的labels标签
五、类名定位元素,类名有空格
//类名有空格不行,被当做复合类无效的,应该去掉后面的空格 driver.findElement(By.className("shop-btn close")).click(); driver.findElement(By.className("shop-btn")).click(); // 定位元素