How to perform search in amazon using selenium.
Solution:
- Create a new Project in Eclipse.
- Add the required libraries for Selenium.
Now in first you need to create an interface: driver
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.remote.DesiredCapabilities;
public interface driver {
public WebDriver wd = new FirefoxDriver();
public static String baseURL = "http://automationpractice.com/index.php";
public static String driverPath = "F:\\Work Environment\\MyProject\\gekodriver\\geckodriver.exe";
public void CallDriver();
public static String email = "rahul@gmail.com";
public static String password = "pass1234";
public static Logger log = Logger.getLogger(driver.class.getName());
public static WebElement mainMenu = null;
public static Action actions = null;
}
Now create a new TestNG Class and enter the following script:
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
public class Search1 implements driver {
public static WebElement se;
@BeforeTest
public void CallDriver() {
System.setProperty("webdriver.gecko.driver",driverPath );
wd.manage().window().maximize();
wd.get("https://www.amazon.com/");
log.debug("Navigated to Amazon.com");
}
@Test
public void TestSearch() {
WebElement se = wd.findElement(By.id("twotabsearchtextbox"));
se.sendKeys("iphone");
log.debug("Entered a keyword to search");
wd.findElement(By.id("nav-search-submit-button")).click();
log.debug("Search button is clicked");
}
@Test
public void TestSearch1() {
String actRe = wd.getCurrentUrl();
String exres = "https://www.amazon.com/s?k=iphone&ref=nb_sb_noss_2";
Assert.assertEquals(actRe,exres);
se.clear();
}
@Test
public void TestSearch2() {
wd.navigate().back();
log.debug("nvigated back to previous page");
System.out.println(wd.getCurrentUrl());
}
@AfterTest
public void afterTest() {
wd.quit();
}
}