Anand Ramamurthy
Anand Ramamurthy

Reputation: 93

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;
    }
}

Upvotes: 0

Views: 1057

Answers (2)

JeffC
JeffC

Reputation: 25746

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.

Upvotes: 1

Saurabh Gaur
Saurabh Gaur

Reputation: 23835

You need to implement some wait before finding the list as below :-

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();

//wait..
Thread.sleep(2000);

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

//now traverse over the list and check
for(WebElement el : linkList)
{
    String link = el.getAttribute("href");
    if((link !=null) && (link.contains("http://www.hdmi.org/")))
    {
        el.click();
        break;
    }
}

For more better solution you can use WebDriverWait here to find that link only without using loop as below :-

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

WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement link = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(@href,'http://www.hdmi.org/')]")));
link.click();

Hope it will help you...:)

Upvotes: 1

Related Questions