I am faced with a challenge of clicking on a specific element on a dynamically loaded page, where the web element is generated as we scroll down the page, similar to the setup on a Jabong webpage.
Here is the code I tried on the Jabong webpage:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.jabong.com/men/clothing/"
+ "?source=topnav");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("Close the modal popup");
driver.findElement(By.id("jab-vchr-cls")).click();
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
/**
* The while(true) loop is necessary to continuously search for the element until it is found.
* We try to find the element within a try-catch block, and if an exception occurs, we scroll
* the page and try to find the element again.
*/
while(true) {
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,100)", "");
try {
WebElement element = driver.findElement(By.xpath("//*[@id='http: //static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img"));
Wait<WebDriver> wait_element=new WebDriverWait(driver, 10);
wait_element.until(ExpectedConditions.elementToBeClickable(element));
element.click();
System.out.println("!!!!!!!!!!!!!!At Last Get Success!!!!!!!!!!!!!!!!");
break;
}
catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
}
}
My inquiry is:
1. Are there more efficient ways to achieve this task?
2. What can be done to optimize the script for faster execution?