简体   繁体   中英

Unable to locate anchor element(href) with javascript in webpage in selenium webdriver(chrome)

I am pretty much new to selenium. I have referred previous posts and found out how to click an element using javaScriptExecutor. But unfortunately, it is not working and i can;t where I am going wrong. Below is the code snippet and some screenshots:

This is how i found out the Xpath in chrome:

Code :

    @Test
public void Search(){
    try{

        WebElement element = driver.findElement(By.xpath("//a[contains(@href,\"javascript:__doPostBack('lbSearch','')\")]"));
        JavascriptExecutor executor = (JavascriptExecutor)driver;
        executor.executeScript("arguments[0].click()", element);
    }
    catch(Exception e){
        System.out.println("Search element not found."+ e.getStackTrace());
    }

Result :

Thankx in advance!

Instead of JavaScriptExecuter you can also click normally by selenium function library.

Your xpath will be //*[@id='lbSearch']

You can click using below code,

@Test
public void Search(){
     WebElement element = null;
    try{

       element = driver.findElement(By.xpath("//*[@id='lbSearch']"));
    }
    catch(Exception e){
        System.out.println("Search element not found."+ e.getStackTrace());
    }
    element.click();
}

One more thing you have to use implicit and explicit wait for locate element. this link will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM