Error locating the element in selenium2
I am using selenium2.0 with testNG. While on using XPATH or CSS for element to locate its shows error “unable to locate the element” . I have programmed in Java as below:
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();
}
}
publ开发者_如何学Pythonic 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();
}
}
Please help me on this. Thanks in advance…
Make Sure XPath/CSS Query is Correct
Download something like Firefinder or anything else where you can test the XPath query directly on the page. Once you know for sure that your query is correct, then you can narrow down the problem in Selenium.
Narrow Down the Problem in Selenium
For example, if your query "//a[@id='cq-gen100']/em/span/span"
is not working, try the base of the query and see if Selenium finds it (don't worry about click for now). Increment from there until the error appears again.
Example:
driver.findElement(By.xpath("//a[@id='cq-gen100']"); //works? driver.findElement(By.xpath("//a[@id='cq-gen100']/em"); //works? driver.findElement(By.xpath("//a[@id='cq-gen100']/em/span"); //works? //etc
I have used driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); to wait for some time, Noew its working.
精彩评论