Selenium/Java没有这样的元素在主页链接之后的页面元素异常



自动化新手,可以在这里获得一些帮助。

我在这个网站上使用Selenium Webdriver和Java——Webdriver University,到目前为止,这段代码一直在向"No Soke Element"抛出异常;element.click(("步骤(即,在页面上找不到元素(:

driver.manage().window().maximize();
driver.get("http://webdriveruniversity.com");
Thread.sleep(3000);
// Follow the link to another page
WebElement link = driver.findElementByXPath("(//div[@class="section-title"])[6]");
link.click();
Thread.sleep(3000);
// Click on the element
WebElement element = driver.findElementByXPath("(//button[@class='accordion'])[1]");
element.click();

然而,当我直接转到链接页面时,它会发现元素刚刚好

driver.manage().window().maximize();
driver.get("http://webdriveruniversity.com/Accordion/index.html");
// Click on the element
WebElement element = driver.findElementByXPath("(//button[@class='accordion'])[1]");
element.click();

我使用了等待元素可见性和线程睡眠,结果相同。你知道这里的问题是什么吗?

您注意到当您单击链接时,页面会在新选项卡中打开吗?这是你的问题。你需要切换到新的选项卡。

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //here you are switch to second tab

希望下面的代码能解决您的问题

Used the getWindowHandles() to capture handle of newly opened tab and switch to the 
tab
// Follow the link to another page
WebElement link = driver.findElement(By.xpath("(//div[@class="section-title"][6]"));
link.click();
Set<String> allWindow = driver.getWindowHandles();
Iterator<String> itr = allWindow.iterator();
while (itr.hasNext()) {
String wind = itr.next().toString();
driver.switchTo().window(wind);
}
Thread.sleep(3000);
// Click on the element
WebElement element = driver.findElement(By.xpath("(//button[@class='accordion'][1]"));
element.click();
Thread.sleep(3000);
driver.close();
}

最新更新