Friday, December 21, 2012

How to click on a element with specific Text

How we will click on a element(Link/button/any element) with a specific Text.

In the below example i open Yahoo Website and look for an element called "Mail", if it found it clicks on the link else it reports Exception saying String not found.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class ClickLinkByText
{
    public static void main(String[] args)
    {
        String s_URL="http://www.yahoo.com";
        String s_SearchLink="Mail";
        WebDriver driver=new FirefoxDriver();
        driver.get(s_URL);
        try
        {
            driver.findElement(By.xpath("//*[@title='"+s_SearchLink+"']")).click();
        }
        catch(Exception e)
        {
            System.out.println("Searched string not found");
        };
    }
}