Tuesday, September 27, 2016

How to click on a link or button in selenium webdriver


If you are new to Selenium Webdriver, please follow the steps in below link to successfully setup Selenium Webdriver on your machine.


If you have already setup Selenium Webdriver, please follow the steps to click on a link or button.

1. Launch webpage where your link or button is available.
2. Open firepath tab in firebug console
3. Click on inspect mouse icon displayed on top left in firebug console
4. Now click on the link or button you want to click using Selenium Webdriver
5. Once you have clicked on the link or button, the Xpath text field in firepath tab will display a xpath value
6. Copy the xpath
7. Now add this xpath and add it into your code as displayed below

Let's do it with an example to click on google plus profile pic in my blog

package <Your package name here>;

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

public class <YourClassNameHere>{

public static void main(String[] args) throws InterruptedException 
{
WebDriver driver = new FirefoxDriver();
driver.get("http://sushilsingh7688.blogspot.in/");
driver.findElement(By.xpath(".//*[@id='Profile1']/div/a[1]/img")).click();
Thread.sleep(5000);
driver.quit();
}
}

Note: 
1. To run above code in eclipse, you must have firefox version latest-2 installed on your machine and selenium-java dependency added in your pom.xml file.
2. This xpath is very elementary and can fail even if there are minor changes in webpage code. when learning more in selenium webdriver, we can create customized xpath which are smaller and more reliable to success.

If you still face any issue in running the code, write to me in comments section.

2 comments: