首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在selenium2中定位元素时出错

问在selenium2中定位元素时出错
EN

Stack Overflow用户
提问于 2011-09-13 14:45:25
回答 2查看 597关注 0票数 0

我在testNG中使用selenium2.0。当使用XPATH或CSS为元素定位时,会显示错误“unable to locate the element”。我已经用Java编写了如下代码:

代码语言:javascript
复制
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();




    }

}

请在这方面帮帮我。预先感谢…

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-16 18:18:53

我用过driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);等了一段时间,没看到它起作用了。

票数 0
EN

Stack Overflow用户

发布于 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7397823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档