For an optimal and systematic execution of tasks, it is highly recommended to adopt a methodical and strategic approach. Follow this comprehensive step-by-step guide:
- Initialize the WebDriver: Begin your testing setup by initializing the WebDriver with the following Java code snippet:
WebDriver driver = new ChromeDriver();
- Navigate to the Destination URL: Direct the WebDriver to your desired URL with the get method:
driver.get("https://www.amazon.in/");
- XPath Identification: Identify the target element using XPath, utilizing attributes such as ID, class, or text for precise selection. Create a WebElement for subsequent interaction.
- For instance, let's identify the search bar:
String searchBoxXPath = "//input[@id='twotabsearchtextbox']";
WebElement searchAmazonIn = driver.findElement(By.xpath(searchBoxXPath));
- Text Input : Enter the desired text for your Amazon search using the sendKeys() method:
searchAmazonIn.sendKeys("Laptop");
- Amazon Search Button XPath: Identify and click the Amazon search button with the relevant XPath:
driver.findElement(By.xpath("//input[@id='nav-search-submit-button']")).click();
- Choosing the Preferred Laptop from the Search Results: After obtaining the search results, our next step is to select a laptop. Utilize XPath to precisely identify and click on the desired laptop:
String desiredLaptopXPath = "(//span[@class='a-size-medium a-color-base a-text-normal'])[1]";
driver.findElement(By.xpath(desiredLaptopXPath)).click();
- Switching and Closing Tabs:Capture the current window handle, get all window handles into a list, switch to the new tab, perform actions and efficiently close the newly opened tab. Achieve this with the following code snippet:
List<String> windowHandles = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(windowHandles.get(index)); //specify the index
driver.close();
By following these straightforward steps, you'll seamlessly handle your testing tasks while adhering to the best practices in automation. This approach guarantees reliability, precision, and an overall improvement in the efficiency of your testing efforts.