我正在为一些网站创建一个自动测试,我正在使用WebDriver和用Java编写的代码。我在这里面临两个问题。
click()
方法无效。size()
。我的代码:
System.setProperty("webdriver.gecko.driver", "D:\\back up\\Proj\\selenium\\Jars\\Drivers\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.americangolf.co.uk/golf-clubs/fairway-woods");
List<WebElement> allBrands = driver.findElements(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/ul/li/a"));
List<WebElement> allBrandsInShowAll = driver.findElements(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/div[2]/ul/li/a"));
System.out.println("Total No of Brands "+(allBrands.size() + allBrandsInShowAll.size()));
driver.findElement(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/div[1]/a")).click(); // This is not clicking on ShowAll Button
for(WebElement ele :allBrandsInShowAll) {
System.out.println("Name=>"+ele.getText());
}
for(WebElement ele :allBrands) {
System.out.println("Name=>"+ele.getText()); // Not printing the names of Brands
}
答案 0 :(得分:0)
您只需使用css选择器div.showall
点击品牌选项中的ShowAll按钮即可。
driver.findElement(By.cssSelector("div.showall")).click();
甚至这个xpath直接工作
driver.findElement(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/div[1]/a")).click()
您获取getText()
所使用的父元素不正确
List<WebElement> allBrands = driver.findElements(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/ul/li/a"));
这将获得单个a
子项中的所有li
标记元素。您需要进入所有li
个孩子并获取他们的锚文本。
你需要这样的东西
WebElement parentElement = driver.findElement(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/ul"));
List<WebElement> allBrands = parentElement.findElements(By.cssSelector("li >a"));
for(WebElement ele :allBrands) {
System.out.println("Name=>"+ele.getText());
}
将输出打印为
名称=&GT; CobraGolf (14)
名称=&GT; CallawayGolf (10)
名称=&GT;泰勒梅 (8)
编辑:OP提到,点击ShowAll
按钮后,他无法获得其他品牌选项。原因是他们在另一个div > ul
孩子里面。
请将您的最终代码修改为 -
//clicks on ShowAll button
driver.findElement(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/div[1]/a")).click();
Thread.sleep(5000);
//gets parent for Categories
WebElement parentElement = driver.findElement(By.xpath("//*[@id='secondary']/div[1]/div[2]/div/ul"));
//gets parent for Categories shown after clicking ShowAll
WebElement secondParentElement = driver.findElement(By.xpath(".//*[@id='secondary']/div[1]/div[2]/div/div[2]/ul"));
List<WebElement> allBrands = parentElement.findElements(By.cssSelector("li >a"));
List<WebElement> allBrandsInShowAll =secondParentElement.findElements(By.cssSelector("li >a"));
System.out.println("Total No of Brands "+(allBrands.size() + allBrandsInShowAll.size()));
for(WebElement ele :allBrands) {
System.out.println("Name=>"+ele.getText());
}
for(WebElement ele :allBrandsInShowAll) {
System.out.println("Name=>"+ele.getText());
}
driver.quit();
}
}
这将打印品牌内的所有类别 -
品牌总数13