How to handle with Google Cookies window in Selenium - java

I can not find a way to handle with the Google Cookies window at the first navigation to google.com. I would like accept the cookies but I can not scroll down on the page.
screenshot here
I guess focus is staying on the main page which is google.com but I could not switch to the cookies window. I have tried the iframe swithc, alert or popup iterator. None of them did not work. Any suggestion is appreciated.

This works just fine:
String chromedriverPath = System.getProperty("user.dir") + "\\resources\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
options.addArguments("--disable-notifications");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.google.com");
driver.findElement(By.id("L2AGLb")).click();

Related

Selenium: Trying to login but the same page is reloaded after click

I am trying to login a page.
I entered the e-mail & password inputs by element.sendKeys() without any error.
After that I need to click the 'loginButton' button. But the button is defined as non keyboard-focusable.
When I run the automation, the button is clicked. But the automation is not continue with the next page (main page); just reloads the same page with empty inputs.
I tried several ways to click the button and also tried to enter by using 'ENTER' key;
// **1.**
loginButton.click();
// **2.**
robot.keyPress(KeyEvent.VK_ENTER);
// **3.**
Actions act = new Actions(dDriver);
act.moveToElement(driver.findElement(By.id("loginButton"))).click().build().perform();
// **4.**
JavascriptExecutor executor;
All of them seems that I can click the button but after that as I mentioned, the page is reloaded, not continue with the next page.
What else can I try?
A problem I can think about is that you are typing the information too fast and hit the login button right away.
Try to wait before clicking the Login button 0.3 seconds:
Thread.Sleep(300);
Or even a full second:
Thread.sleep(1000);
Tell me if this solves your issue.
Also, the site might be disabled for automation code so add these to your ChromeOptions:
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
WebDriver driver = new ChromeDriver(options);
Or
options.addArguments("disable-infobars");
To click() on the element Giriş Yap you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.green_flat#loginButton"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='green_flat' and #id='loginButton'][text()='Giriş Yap']"))).click();

org.openqa.selenium.ElementClickInterceptedException: element click intercepted error using Selenium and Java in headless mode

I have a project that I am working on with java and selenium.
the test work OK in UI mode.
However in headless mode I get this error
org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element <label _ngcontent-yrc-c26="" formcontrolname="reportingDealPermission" nz-checkbox="" class="ant-checkbox-wrapper ng-untouched ng-pristine ng-valid" ng-reflect-name="reportingDealPermission">...</label> is not clickable at point (161, 562). Other element would receive the click: <div _ngcontent-yrc-c26="" class="footer">...</div>
how can I resolve this issue (working in UI mode). this is my code
WebDriver driver = getWebDriver();
WebElement element;
Thread.sleep(60000);
element = driver.findElement(By.xpath("//label[#formcontrolname='reportingDealPermission']"));
element.click();
why in selenium there is no operation to move to the element and break all layers.
this is the UI.
this is working in UI mode not working in headless mode, made sleep for 6 minutes and not resolved so this is not time issue
This error message...
org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element <label _ngcontent-yrc-c26="" formcontrolname="reportingDealPermission" nz-checkbox="" class="ant-checkbox-wrapper ng-untouched ng-pristine ng-valid" ng-reflect-name="reportingDealPermission">...</label> is not clickable at point (161, 562). Other element would receive the click: <div _ngcontent-yrc-c26="" class="footer">...</div>
...implies that the click on the desired element was intercepted by some other element.
Clicking an element
Ideally, while invoking click() on any element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(getWebDriver(), 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("label[formcontrolname=reportingDealPermission][ng-reflect-name=reportingDealPermission]"))).click();
xpath:
new WebDriverWait(getWebDriver(), 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#formcontrolname='reportingDealPermission' and #ng-reflect-name='reportingDealPermission']"))).click();
Update
After changing to headless if it still doesn't works and still get exception there still a couple of other measures to consider as follows:
Chrome browser in Headless mode doesn't opens in maximized mode. So you have to use either of the following commands/arguments to maximize the headless browser Viewport:
Adding the argument start-maximized
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
Adding the argument --window-size
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--window-size=1400,600");
WebDriver driver = new ChromeDriver(options);
Using setSize()
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().setSize(new Dimension(1440, 900));
You can find a detailed discussion in Not able to maximize Chrome Window in headless mode
Additionally, you can also wait for the intercept element to be invisible using the ExpectedConditions invisibilityOfElementLocated before attempting the click() as follows:
cssSelector:
new WebDriverWait(getWebDriver(), 10).until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("div.footer")));
new WebDriverWait(getWebDriver(), 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("label[formcontrolname=reportingDealPermission][ng-reflect-name=reportingDealPermission]"))).click();
xpath:
new WebDriverWait(getWebDriver(), 10).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[#class='footer']")));
new WebDriverWait(getWebDriver(), 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#formcontrolname='reportingDealPermission' and #ng-reflect-name='reportingDealPermission']"))).click();
References
You can find a couple of related relevant discussions in:
Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click
Element MyElement is not clickable at point (x, y)… Other element would receive the click
Try adding an explicit wait
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#formcontrolname='reportingDealPermission']"))).click();
and if this doesn't work then try using the JS Executor
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#formcontrolname='reportingDealPermission']")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
None of the above answers worked for me. Try using action class as follows:
WebElement element = driver.findElement(By.xpath("//div[#class='footer']"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
For this issue:
org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element <label _ngcontent-yrc-c26="" formcontrolname="reportingDealPermission" nz-checkbox="" class="ant-checkbox-wrapper ng-untouched ng-pristine ng-valid" ng-reflect-name="reportingDealPermission">...</label> is not clickable at point (161, 562).
Another element receives the click:
Answer is to explicitly wait with javascript executor. This combination is working for me:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#formcontrolname='reportingDealPermission']")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
WebDriverWait wait = new WebDriverWait(driver, 10); ---> has deprecated and it gives an error. Please use below instead:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#formcontrolname='reportingDealPermission']"))).click();
Ensure to import relevant items for the WebDriverWait and ExpectedConditions.
In my case "JavaScript" works:
WebElement ele = driver.findElement(By.xpath("(//input[#name='btnK'])[2]"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click()", ele);
It was taken from:
http://makeseleniumeasy.com/2020/05/25/elementclickinterceptedexception-element-click-intercepted-not-clickable-at-point-other-element-would-receive-the-click/
Answer is worked for me.
Please check the below sreenshot for the my problem reference.
Below alert is comes in between the the my button and frame.
enter image description here
In my case, nothing worked. Only the THREAD.SLEEP() method worked!

How to open new tab in Selenium 3 in java

Before tagging this as duplicate. Please read the Question. i have seen many answers for this kind of question. But none of them really worked.
System.setProperty("webdriver.gecko.driver", "src/test/driver/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
driver.get("https://www.facebook.com");
this my code. When I run this instead of opening a new tab its just opening in Current tab.How can i open second link in new tab?
You can use javascript for this in ur selenium code :-
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open('https://www.google.com','_blank');");

Downloading pdf with Selenium WebDriver for Firefox

I am trying to download a .pdf to my local so that I can use Apache PDFBox to read the text from it and verify it as a part of my test suite. I have already found some code to download the pdf from Firefox by hitting a URL. This does not work for me since the pdf I am working with is a confidential document so it is not exposed by a URL, instead loaded within PDF Viewer as a popup window. Does anyone know how to hit the download button within the Firefox PDF Viewer after I have loaded the PDF Viewer in the browser?
I have tried looking it up by the element's id which = "download":
(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("download")));
driver.findElement(By.id("download")).click();
Unfortunately this does not work as it says it cannot find the element. Anyone know a workaround?
UPDATE: The pop-up window I described was an iframe element. This caused the inability to find the "download" element. Fixed with #4M01's switchTo() answer.
As you mentioned,
instead loaded within PDF Viewer as a popup window
You need to handle switching between different windows using switchTo() method of the driver object.
Below code working fine for me without an issue and I'm able to click on download icon.
public class FirefoxPDFTest {
WebDriver driver;
#BeforeClass
void Setup(){
System.setProperty("webdriver.gecko.driver", "C:\\Automation\\Selenium\\drivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Test
void downloadPDF(){
driver.get("http://www.pdf995.com/samples/pdf.pdf");
waitTillPageLoad();
driver.findElement(By.id("download")).click();
}
private void waitTillPageLoad(){
new WebDriverWait(driver, 30).until(driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete"));
}
#AfterClass
void tearDown(){
driver.close();
driver.quit();
}
}
just use following code for clicking download button:
driver.findElement(By.xpath("//button[#id='download']")).click();
Thread.sleep(8000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
We can handle the download popup in Firefox browser using Firefox browser settings and Firefox Profile setting using WebDriver.
Step 1: Update the setting in Firefox browser.
Open Firefox browser and navigate to Tools -> Options
Navigate to Applications.
Set the Action type as ‘Save File’ for PDF.
Step 2: Initialize FireFoxDriver using FirefoxProfile
File downloadsDir = new File("");
// Set Preferences for FirefoxProfile.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
// Initialize the FireFoxDriver instance.
FirefoxDriver webDriver = new FirefoxDriver(profile);
Step 3: Execute the Script
Execute the script which clicks on the download PDF icon.
Result: PDF file will be downloaded and the Download popup will not be displayed.
You can handle the download icon (using Firefox), by using the following (C#) code:
IWebElement element = Driver.FindElement(By.Id("download"));
IJavaScriptExecutor executor = (IJavaScriptExecutor)Driver;
executor.ExecuteScript("arguments[0].click();", element);

Unable to access link menu options using webdriver

I am using selenium webdriver. I am unable to access link menu options.eg:I want to access options "Casual shoes" option under "Men" menu link from flipkart site. i tried using below code
WebElement a= driver.findElement(By.xpath("//a[title='Men']"));
a.click();
but unable to click on menu link "Men"
Your XPath is wrong you forget to add # in front of attribute. You are using //a[title='Men'] but you should use //a[#title='Men']
Below code is working for me:-
driver.get("http://www.flipkart.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[#title='Men']")).click();
driver.findElement(By.xpath("//span[contains(.,'Casual Shoes')]")).click();
OR
In chrome below code is working fine for me:-
WebElement we =driver.findElement(By.xpath("//a[#title='Men']"));
we.click();
WebElement Causual =driver.findElement(By.xpath("//span[contains(.,'Casual Shoes')]"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", Causual);
Hope it will help you :)

Categories