我在testNG中使用selenium2.0。当使用XPATH或CSS为元素定位时,会显示错误“unable to locate the element”。我已经用Java编写了如下代码:
public class mytest {
public static WebDriver driver;
public Alert alert;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
driver=new FirefoxDriver();
driver.get("http://localhost:4503/xyz.html");
}
public static void clickButton(WebDriver driver, String identifyBy, String locator){
if (identifyBy.equalsIgnoreCase("xpath")){
driver.findElement(By.xpath(locator)).click();
}else if (identifyBy.equalsIgnoreCase("id")){
driver.findElement(By.id(locator)).click();
}else if (identifyBy.equalsIgnoreCase("name")){
driver.findElement(By.name(locator)).click();
}
}
public static void typeinEditbox(WebDriver driver, String identifyBy, String locator, String valuetoType){
if (identifyBy.equalsIgnoreCase("xpath")){
driver.findElement(By.xpath(locator)).sendKeys(valuetoType);
}else if (identifyBy.equalsIgnoreCase("id")){
driver.findElement(By.id(locator)).sendKeys(valuetoType);
}else if (identifyBy.equalsIgnoreCase("name")){
driver.findElement(By.name(locator)).sendKeys(valuetoType);
}
}
public static void openApplication(WebDriver driver, String url) {
driver.get(url);
}
@Test
public void testAcrolinxApplication() throws InterruptedException {
openApplication(driver,"http://xyz.com");
typeinEditbox(driver,"name","p_user","xxx");
typeinEditbox(driver,"name","p_pas","yyy");
clickButton(driver,"id","input-submit");
/*Up to this its working fine …..
At below line this throws error could not locate the xpath element "//a[@id='cq-gen100']/em/span/span" BUT THIS IS WOKING FINE IN Selenium1.0 api that is with
selenium.click("//a[@id='cq-gen100']/em/span/span"); */
driver.findElement(By.xpath("//a[@id='cq-gen100']/em/span/span")).click();
}
}请在这方面帮帮我。预先感谢…
发布于 2011-09-16 18:18:53
我用过driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);等了一段时间,没看到它起作用了。
发布于 2011-09-13 22:42:14
确保XPath/CSS查询正确
下载Firefinder之类的东西,或者可以直接在页面上测试XPath查询的任何其他东西。一旦确定查询是正确的,就可以在Selenium中缩小问题的范围。
缩小了Selenium中的问题范围
例如,如果您的查询"//a[@id='cq-gen100']/em/span/span"不工作,请尝试查询的基础,看看Selenium是否能找到它(现在不用担心单击)。从那里开始递增,直到错误再次出现。
示例:
driver.findElement(By.xpath("//a@id='cq-gen100'");//工作吗?driver.findElement(By.xpath("//a@id='cq-gen100'/em");//工作吗?driver.findElement(By.xpath("//a@id='cq-gen100'/em/span");//工作? //etc
https://stackoverflow.com/questions/7397823
复制相似问题