在selenium2中定位元素时出错

时间:2011-09-13 06:45:25

标签: selenium selenium-rc selenium-webdriver

我正在使用selenium2.0和testNG。在使用XPATH或CSS元素来定位其显示错误“无法找到元素”时。 我用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();




    }

}

请帮我解决这个问题。 提前谢谢......

2 个答案:

答案 0 :(得分:1)

确保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”); //有效吗?   //等

答案 1 :(得分:0)

我用过 driver.manage()。timeouts()。implicitlyWait(10,TimeUnit.SECONDS); 等一段时间,Noew工作。