Search code examples
seleniumhref

Unable to click on href link using selenium


I am unable to open a href link using the code below. I have used the code to store the tag names as web elements and iterated to point to my target href. Please kindly suggest what to change in the above code as the output indicates that there are null references.

String path="http://google.com";

WebDriver driver = new ChromeDriver();
driver.get(path);
driver.manage().window().maximize();

driver.findElement(By.name("q")).sendKeys("hdmi");
driver.findElement(By.name("btnG")).click();


//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
    if(linkList.get(i).getAttribute("href").contains("http://www.hdmi.org/"))
    {
        linkList.get(i).click();
        break;
    }
}

Solution

  • You don't have to loop through the links in this case. You can just locate the one you want and click on it. You will have to have a brief wait as the results load or it won't work. I'm guessing that's why your code wasn't working.

    driver.findElement(By.name("q")).sendKeys("hdmi");
    driver.findElement(By.name("btnG")).click();
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href*='http://www.hdmi.org/']"))).click();
    

    NOTE: There is more than one link that matches your requirements but this code clicks only the first one.