In this tutorial, we will let you know how to click on an image in Selenium WebDriver. When a user clicks on an image it redirects the user to a different window or page. As shown in the below image, when the user clicks on the "Facebook" logo, it redirects to the homepage.
In the below example, we will access the "Facebook" logo on the upper left portion of Facebook's Password Recovery page.
Scenario:
- Go to this URL https://www.facebook.com/login/identify?ctx=recover
- Click on Facebook logo
- The home page will show
1) Click on image By using XPath
import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; public class ClickOnImageByXpath { public static void main(String[] args) { String baseUrl = "https://www.facebook.com/login/identify?ctx=recover"; System.setProperty("webdriver.gecko.geckodriver", "/home/khawer/eclipse-workspace/TrainingVideos/geckodriver"); FirefoxDriver driver = new FirefoxDriver(); driver.get(baseUrl); driver.findElement(By.xpath("//a[@href = 'https://web.facebook.com/']")).click(); if (driver.getTitle().equals("Facebook – log in or sign up")) { System.out.println("We are at Facebook's homepage"); } else { System.out.println("We are not at Facebook's homepage"); }
2) Click on image By using CssSelector
import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; public class ClickOnImageByCssSelector { public static void main(String[] args) { String baseUrl = "https://www.facebook.com/login/identify?ctx=recover"; System.setProperty("webdriver.gecko.geckodriver", "/home/khawer/eclipse-workspace/TrainingVideos/geckodriver"); FirefoxDriver driver = new FirefoxDriver(); driver.get(baseUrl); driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click(); if (driver.getTitle().equals("Facebook – log in or sign up")) { System.out.println("We are at Facebook's homepage"); } else { System.out.println("We are not at Facebook's homepage"); } } }
0 comments:
Post a Comment