Selenium Webdriver - Clicking on Banner - selenium

I am trying to click on < and > button of the banner which keeps on rotating after few seconds in amazon.in but unable to do so.
I wrote the following code but still not successful
driver.get("amazon.in");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//span[contains(text(),'Previous page')]")).click();
It does not click on < button on the banner which is displayed on the top of the page.

When I write code that I'm likely to reuse, I put it into functions. Here's a function to click the next and prev arrows on the banner.
public static void clickNextBanner()
{
driver.findElement(By.cssSelector("a.a-carousel-goto-nextpage")).click();
}
public static void clickPrevBanner()
{
driver.findElement(By.cssSelector("a.a-carousel-goto-prevpage")).click();
}

Try using Explicit Wait
WebElement previous =driver.findElement(By.xpath("//span[contains(text(),'Previous page')]"));
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(text(),'Previous page')]")));
previous.click();

Use the following code to click on next > and previous < arrows of slider.
driver.get("http://www.amazon.in/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Forward navigation
for(int i =0;i<3;i++)
{
driver.findElement(By.xpath("//a[#class='a-carousel-goto-nextpage']")).click();
Thread.sleep(1000);
}
// back navigation
for(int j=0;j<3;j++)
{
driver.findElement(By.xpath("//a[#class='a-carousel-goto-prevpage']")).click();
Thread.sleep(1000);
}

Related

I am trying to automate Flipkart where while trying to click on submenu of the header menu it is getting detaching from the DOM, how to handle this?

The submenus are getting appeared in the DOM only when we hover over the main menu.
So after hovering over main menu using Actions class the submenus are coming, but then again when I am trying to get into the submenu it is getting detached from the DOM.
Please help me on this.
public void goToMenTopWearSectionFromFashion() throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Actions act=new Actions(driver);
try {
act.moveToElement(FashionHeaderLink).perform();
}
catch(Exception e)
{
act.moveToElement(driver.findElement(By.xpath("//div[#class='_1psGvi SLyWEo']//div[text()='Fashion']"))).perform();
}
try {
if(driver.findElement(By.xpath("//*[#class='_3XS_gI _7qr1OC']//a[1]")).isDisplayed())
{
System.out.println(driver.findElement(By.xpath("//*[#class='_3XS_gI _7qr1OC']//a[1]")).isDisplayed());
driver.findElement(By.xpath("//*[#class='_3XS_gI _7qr1OC']//a[1]")).click();
}
}catch(Exception e) {e.printStackTrace();}
}
After the hover, trying to move to click on Men's Top Wear was sometimes causing it to disappear along the way. I experienced the same by hand if I moved diagonally rather than straight down. Instead,in your 2nd try block you can do the following:
if(driver.findElement(By.linkText("Men's Top Wear")).isDisplayed())
{
String urlSave = driver.findElement(By.linkText("Men's Top Wear")).getAttribute("href");
driver.get(urlSave);
}
Probably it would work with your locator, too.

Switch focus to reopened tab in Chrome - selenium

I am trying to achieve the below flow in selenium ,
click on a link to open new tab(child1) from parent window
close the driver (child1) after performing certain actions
Open the same link(child1) again to perform another set of actions
I am able to achieve the first two steps successfully by switching focus. But I am stuck at the third step where I am not able to focus on the same reopened tab. I get the below error,
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
public class abc {
String currentWindow = driver.getWindowHandle();
public void action1() {
//Click on main menu that open a new tab
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(currentWindow)) {
driver.switchTo().window(handle);
}
//Perform the actions
driver.close();
driver.switchTo().window(currentWindow);
}
public void action2(){
//Click on main menu which reopen the same tab
for (String handle : driver.getWindowHandles()) {
if (!handle.equalsIgnoreCase(currentWindow)) {
System.out.println("Port Response : switch focus");
driver.switchTo().window(handle);
break;
}
}
//perform a set of actions
driver.close();
driver.switchTo().window(currentWindow);
}
}//end of abc
I want to create the actions more like a reusable independent action so I would like to close all tabs and reopen them again for other set of action. Please let me know if you need any more details on this.

How do i tell Selenium to wait until report get ready to download

After the selection of date from the date picker,clicking on 'View Report' button and then its take a time to generate the report and then it download the report.. My following code is working without an error but how do i use fluent wait instead of Thread.sleep(20000),(last line in below code). For fluent or explicit wait i ask to wait for what condition? Also wanted to verify whether the file has been downloaded or not with assertion. Any help will be appreciated.
public void generateReport() throws Exception {
clickDatePicker.click();
log.info("Select the Date from datepicker");
Select month = new Select(selectMonth);
month.selectByValue("0");
log.info("Selected the Month from datepicker");
Select year = new Select(selectYear);
year.selectByValue("2020");
log.info("Selected the Year from datepicker");
act.moveToElement(selectDate).click().build().perform();
buttonViewReport.click();
log.info("Finally clicked on Get Report button ");
Thread.sleep(20000);
}
Check the below method, which will make sure the script will wait until the download is started (for max of the minutes specified in the method call)
public void waitUntilDownloadStarted(WebDriver driver, int maxWaitTimeInMinutes) throws InterruptedException {
// Store the current window handle
String mainWindow = driver.getWindowHandle();
// open a new tab
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.open()");
// switch to new tab
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// navigate to chrome downloads
driver.get("chrome://downloads");
Instant startTime = Instant.now();
int elapsedTime = (int) Duration.between(startTime, Instant.now()).toMinutes();
// wait until the download is started
while ( (Long)js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelectorAll('#downloadsList downloads-item').length") == 0) {
Thread.sleep(1000);
elapsedTime = (int) Duration.between(startTime, Instant.now()).toMinutes();
if (elapsedTime > maxWaitTimeInMinutes) {
break;
}
}
// close the downloads tab2
driver.close();
// switch back to main window
driver.switchTo().window(mainWindow);
}
Tested as below.
waitUntilDownloadStarted(driver, 10);
Does anything appears like that your download has been generated? or inspect any change in HTML. then you can use the following code to wait until change appears.
WebDriverWait wait=new WebDriverWait(driver, 20000);
wait.until(ExpectedConditions.numberOfElementsToBe(locator, number));
where 20000 is time in milliseconds

Handling a button that opens a new tab and redirects you to it

After clicking the create invoice button, it opens a new tab and redirects you to it. Next, it should click a button but it says no element exists. Did it search the element on the current page ? not on the new tab?
Tried explicit wait for that button and tried switching back and forth to the tab
#Test (priority=3)
public void ProductListExpress() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase.php");
String newUrl1 = driver.getCurrentUrl();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase page ");
}
else {
System.out.println("Failed in proceeding to Purchase page");
}
}
#Test (priority=4)
public void ClickInvoice() {
}
#Test (priority=5)
public void test() {
//Click create invoice button
driver.findElement(By.name("btncreateinvoice")).click();
System.out.println("Successful in clicking create invoice");
}
Expect to click button after redirecting.
First of all wait for 2nd window to open and be available to the WebDriver. You can use Explicit Wait for this like:
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfWindowsToBe(2));
Check out How to use Selenium to test web applications using AJAX technology article for more information on the concept
Once you have the confidence that the number of windows is 2 you can use switchTo().window() function to change the context for the 2nd window:
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));
When you are clicking on new button, new tab is getting open. In this scenario, you need to use WindowsHandles. Try below code:
#Test (priority=3)
public void ProductListExpress() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase.php");
Set<String> winHandles= driver.getWindowHandles();
Iterator<String> it = winHandles.iterator();
String parentWindowId = it.next();
String newWindowID= it.next();//Here you will get windows id of newly opened tab
driver.switchTo().window(newWindowID); //now your driver is switching to new tab
String newUrl1 = driver.getCurrentURL();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase page ");
}
else {
System.out.println("Failed in proceeding to Purchase page");
}
}
You can switch to new tab with this way :
//Click create invoice button
driver.findElement(By.name("btncreateinvoice")).click();
System.out.println("Successful in clicking create invoice");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
during execution whenever a new tab or window opens, control of the driver still remains in the original tab or window unless we write couple of lines of code to manually switch the control to new tab or window.
In your case, Since the driver control is still in original tab and next element to click is in new tab, selenium is not able to find it, hence it says no element exists
#Test (priority=5)
public void test() {
WebDriverWait w= new WebDriverWait(driver, 10);
ArrayList<String> x = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(x.get(1)); // here x.get(1) indicates that
driver control is switched to new tab or new window
w.until(ExpectedConditions.elementToBeClickable("locator of button to be clicked"));
}
In case ,in your next steps if you can to continue execution in the original window or tab, you have to again switch selenium driver control back .
driver.switchTo().window(x.get(0));// during next steps if you want
driver control to switch back to original tab or window you have to write this line
of code
IDK if this is what you're asking, but it might be. I was CTRL+CLICKING a button to open a new tab. This is how I found the tab:
Set<String> curWindows = new HashSet<> (driver.getWindowHandles ());
String newWindowHandle = null;
a.keyDown(Keys.LEFT_CONTROL).click(THE_BUTTON).keyUp(Keys.LEFT_CONTROL).build().perform();
this.delay (500);
for (String windowHandle : driver.getWindowHandles ()) {
if (curWindows.contains (windowHandle) == false) {
newWindowHandle = windowHandle;
break;
}
}
if (newWindowHandle == null) {
log.error ("Unable to find the new window handle.");
return null;
}

Popup freezes Selenium Webdriver until the popup is manually closed

I'm having problems automating tests on an internal website. In some cases, a popup will freeze the test until I manually close the popup. After the popup is opened, no code is run, not even System.out.println's.
driver.findElement(By.id("top_toolbarSALTkA7_Aras_Tbi_promote")).click();
System.out.println("test");
I have tried multiple ways of handling the popup, but no code at all is run after the click(), and it seems it never times out.
Tried:
1.
((JavascriptExecutor) driver).executeScript("return document.getElementById('top_toolbarSALTkA7_Aras_Tbi_promote', 'onClick')");
2.
Set<String> windowHandles = driver.getWindowHandles();
for(String handle : windowHandles)
{
driver.switchTo().window(handle);
if (driver.getTitle().contains(title))
{
System.out.println("- (Page title is: " + driver.getTitle() + ")");
break;
}
}
3.
driver.switchTo().alert();
4.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
If I close the popup, the test will continue with the System.out.println and then continue until finshed.
I'm using Selenium Webdriver 2.48.2 with FireFox 31.0, programming is Java. Any ideas what can be done? (It's not possible to change the website)
Finally found the solution!!! Found it in the Selenium official user group: https://groups.google.com/forum/#!searchin/selenium-users/popup%7Csort:relevance/selenium-users/eDqPiYoJ9-Q/kRI67cCVe5wJ
Solution is to start a new thread that waits a couple of seconds, and then presses enter (or in my case first tabs to the "OK" button). Just call the function before the popup is opened.
public static final void prepareToPressEnterKey(int seconds, int tabs) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Runnable() {
public void run() {
try {
Robot robot = new Robot();
for (int i=0; i<tabs; i++)
{
robot.keyPress(KeyEvent.VK_TAB);
TimeUnit.SECONDS.sleep(1);
robot.keyRelease(KeyEvent.VK_TAB);
}
robot.keyPress(KeyEvent.VK_ENTER);
TimeUnit.SECONDS.sleep(1); //press for 1 sec
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException | InterruptedException e) {
System.out.println("Prepare to Press Enter Exception");
}
}
},
seconds,
TimeUnit.SECONDS);
scheduledExecutorService.shutdown();
}
Still, if there are any better solutions I'd very much like to know. Thanks!
Just disable popup. I mean you need to call the next script inside the current browser context (executeScript - I guess in your, Java binding case):
document.alert = window.alert = alert = () => {};