我是Selenium的新手,我正试图用它测试一个引导程序菜单。
我正在尝试点击下拉菜单中的特定行但是没有这样的元素'。
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class Foo {
@Test
public void tryToClick() throws Exception {
final WebDriver driver =
new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("file:///tmp/foo.html");
WebElement dropdownToggle = driver.findElement(By.xpath("id('dropdown-toggle-id')"));
Actions cursor = new Actions(driver);
cursor.moveToElement(dropdownToggle);
cursor.click();
cursor.perform();
Thread.sleep(1000);
WebElement weh = driver.findElement(By.id("id('id-b')"));
// Now I get ...
// org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"id('id-b')"}
// Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"id('id-b')"}
Actions cursor2 = new Actions(driver);
cursor2.moveToElement(weh);
cursor2.click();
}
}
显示问题的示例页面在这里:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Bootstrap 3 Skeleton - jsFiddle demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<style type='text/css'>
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
});//]]>
</script>
</head>
<body>
<li class="dropdown"> <a href="#" class="dropdown-toggle" id="dropdown-toggle-id" data-toggle="dropdown">
My Menu<b class="caret"></b>
</a>
<ul class="dropdown-menu" id="dropdown-menu-id">
<li><a href="#" id="id-a"> <span class="fa fa-lg fa-user"></span>AA</a>
</li>
<li><a href="#" id="id-b"><span class="fa fa-lg fa-cog"></span>BB</a>
</li>
</ul>
</li>
</body>
</html>
使用JQuery我可以做到这一点似乎没问题:
$("#dropdown-toggle-id").click()
和
$("#id-b").click()
答案 0 :(得分:1)
更改
WebElement weh = driver.findElement(By.id("id('id-b')"));
到
WebElement weh = driver.findElement(By.id("id-b"));
再试一次。
答案 1 :(得分:0)
您可以使用Select(WebElement element);
方法
import org.openqa.selenium.support.ui.Select;
new Select(driver.findElement(By.id("dropdown-toggle-id"))).selectByIndex(1);
或者
new Select(driver.findElement(By.id("dropdown-toggle-id"))).selectByVisibleText("BB");