Handle/Accept cookie pop-up in Selenium - java

I am trying to 'accept the cookies' on the homepage, but my code doesn't work. I tried to get the new window handles and then identify the subsequent Xpath for the frame and Accept button but it never work.
package seleniumTestPack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.Cookie;
#SuppressWarnings("unused")
public class firstSelTest {
public static void main(String[] args) throws InterruptedException {
ChromeOptions options = new ChromeOptions();
//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\vmyna\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.zyyah.com/homeowner-lifestyle-perfected-home-value-protected/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.switchTo().frame(0);
driver.getWindowHandles();
driver.switchTo().alert().accept();
By cookies_accept = By.xpath("//*[#id=\"cookie-law-info-bar\"]");
By cookies_gotIt = By.xpath("//*[#id=\"cookie_action_close_header\"]");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(cookies_accept)).click();
wait.until(ExpectedConditions.invisibilityOfElementLocated(cookies_accept));
wait.until(ExpectedConditions.elementToBeClickable(cookies_gotIt)).click();
driver.findElement(By.xpath("//*[#id=\'et-boc\']/div/div/div[4]/div/div/div[2]/div[1]")).click();
Thread.sleep(10000);
driver.quit();
}
}

You no need to switch frame in your case, because there is no frame present in your page. Just inspect the "Accept Cookies" and click on that.
driver.get("https://www.zyyah.com/homeowner-lifestyle-perfected-home-value-protected/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("cookie_action_close_header")).click();
Use of Switch to Frame:
https://www.browserstack.com/guide/handling-frames-in-selenium
Use of Alert:
https://www.browserstack.com/guide/alerts-and-popups-in-selenium

The code below worked for me. "Accept Cookies" button is not under any pop-window. So no frame or pop-up window is present here. Here, we just need to locate "Accept Cookies" button and click on it.
WebDriver Driver = new ChromeDriver();
Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String url = "https://www.zyyah.com/homeowner-lifestyle-perfected-home-value-protected/";
Driver.get(url);
Driver.findElement(By.id("cookie_action_close_header")).click();
System.out.println("completed");

WebElement cookieAccept = driver.findElement(By.id("gdpr-banner-accept"));
// Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
wait.until(ExpectedConditions.visibilityOf(cookieAccept));
wait.until(ExpectedConditions.elementToBeClickable(cookieAccept));
cookieAccept.click();

Related

How can I auto accept cookies pop windows Automation Java

What is the wrong in my code , why auto click doesn't work in accept cookies button. This website using angular application.
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.paulhammant.ngwebdriver.ByAngular;
import com.paulhammant.ngwebdriver.NgWebDriver;
public class NewClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Hp\\Downloads\\chromedriver_win32\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
NgWebDriver ngWebDriver = new NgWebDriver(driver);
ngWebDriver.waitForAngularRequestsToFinish();
driver.get("https://visa.vfsglobal.com/ind/en/deu/login/");
ngWebDriver = new NgWebDriver((JavascriptExecutor) driver);
ngWebDriver.waitForAngularRequestsToFinish();
driver.findElement(ByAngular.options("onetrust-accept-btn-handler")).click();
}
}
Attached Image here
When you use this line
driver.findElement(ByAngular.options("onetrust-accept-btn-handler")).click();
it will try to find the element immediately, often resulting in errors. Cause web element/elements have not been rendered properly.
This is main reason we should opt for Explicit waits, implemented by WebDriverWait.
They allow your code to halt program execution, or freeze the thread,
until the condition you pass it resolves. The condition is called with
a certain frequency until the timeout of the wait is elapsed. This
means that for as long as the condition returns a falsy value, it will
keep trying and waiting.
Code :
Webdriver driver = new ChromeDriver();
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.id("onetrust-accept-btn-handler"))).click();
As per my knowledge there is no way to auto accept cookies using ChromeOptions you need to find the element and click.
driver = new ChromeDriver();
driver.get("https://visa.vfsglobal.com/ind/en/deu/login/");
new WebDriverWait(driver, 30).until(ExpectedConditions.elementToBeClickable(By.id("onetrust-accept-btn-handler"))).click();
Please add wait functionality before entering username and password,
if pop up interrupt while entering, username and password will not be proper.
In my case, i created a common method wait and click,
dh.wait_for_the_element_then_do(By.xpath("//button[text()='Accept All Cookies']"), "click", "", "cookies popo up");
dh.wait_for_the_element_then_do(By.xpath("//input[#tcp-auto='input-username']"),"send", username, "login username");
dh.wait_for_the_element_then_do(By.xpath("//input[#tcp-auto='input-password']"),"send", password, "login password");
dh.wait_for_the_element_then_do(By.xpath("//span[text()='Sign in']"),"click", "", "signin button");
This is the solution of my problem.
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.paulhammant.ngwebdriver.ByAngular;
import com.paulhammant.ngwebdriver.NgWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.By;
public class NewClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Hp\\Downloads\\chromedriver_win32\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
NgWebDriver ngWebDriver = new NgWebDriver(driver);
ngWebDriver.waitForAngularRequestsToFinish();
driver.get("https://visa.vfsglobal.com/ind/en/deu/login");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions
.elementToBeClickable(By.id("onetrust-accept-btn-handler")))
.click();

Selenium Java - unnable to click on Google Search

I saw a lot of threads with this issue but none is working for me as I tried almost all possible methods and still get error "Exception in thread "main" org.openqa.selenium.ElementClickInterceptedException: element click intercepted"
System.setProperty("webdriver.chrome.driver", "C://Driver//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.findElement(By.xpath("//body/div[1]/div[3]/form[1]/div[2]/div[1]/div[1]/div[1]/div[2]/input[1]")).sendKeys("568567546754");
driver.findElement(By.xpath("//form[#role='search']/div[2]/div[1]/div[3]//center/input[1]")).click();
//driver.findElement(By.xpath("//div[#class='RNNXgb']/div/div[2]/input")).sendKeys("3462355452354");
//Parent-child relationship xpath - Define xpath for parent
//body/div[1]/div[3]/form[1]/div[2]/div[1]/div[1]/div[1]/div[2]/input[1]
//driver.findElement(By.xpath("//body/div[1]/div[3]/form[1]/div[2]/div[1]/div[1]/div[1]/div[2]/input[1]"));
//driver.findElement(By.xpath("//div[#class='FPdoLc tfB0Bf']/center/input[1]")).click();
//driver.findElement(By.xpath("//iframe[contains(#src, 'consent.google.com')]")).click();;
//Thread.sleep(2000);
//driver.findElement(By.xpath("//*[#id='introAgreeButton']/span/span")).click();
//driver.findElement(By.linkText("Google Search")).click();
//driver.findElement(By.id("lst-ib")).sendKeys();
//driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
//driver.findElement(By.name("btnK")).click();
//driver.manage().window().maximize();
Please try this, it will work. As Enter will do the same thing as clicking on the Search button.
driver.findElement(By.name("q")).sendKeys("568567546754" + Keys.ENTER);
Here I'm not using the xpath for search text field as I've found name attribute.
You can send the search text and Enter in one shot.
You can use Action class here.
driver.get("https://www.google.com/");
driver.findElement(By.xpath("//input[#title='Search']")).sendKeys("568567546754");
Robot ab = new Robot();
ab.keyPress(KeyEvent.VK_ENTER);
You can use this reduced Xpath : //input[#name='q'] or driver.findElement(By.name("q")).sendKeys("568567546754");
or you can try this
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("\$x("//input[#name='q']")[0].value="Car"\");
check out this code snippet
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class SearchAction{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","./chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
// identify element
WebElement p=driver.findElement(By.name("q"));
//enter text with sendKeys() then apply submit()
p.sendKeys("Selenium Java");
// Explicit wait condition for search results
WebDriverWait w = new WebDriverWait(driver, 5);
w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//ul")));
p.submit();
driver.close();
}
}

How to click on the svg based Delete icon using Selenium and Java

I got web application, i can login and see a table of transactions. There is icon, i am trying to use webdriver to retrieve icon, i fail to get the icon.
how to click the delete icon and action triggers?
String baseURL = "http://testingapp.workspez.com/login";
driver.get(baseURL);
driver.findElement(By.xpath("//input[#id='field_email']")).sendKeys("rahul#workspez.com");
driver.findElement(By.xpath("//input[#id='field_password']")).sendKeys("Sujeet#19");
driver.findElement(By.className("MuiButton-label")).click();
WebElement generalInfo = driver.findElement(By.xpath("//*[text()='General Info']"));
generalInfo.click();
WebElement md = driver.findElement(By.xpath("//*[text()='Contacts']"));
md.click();
WebElement searchbox = driver.findElement(By.xpath("//input[#class='MuiInputBase-input MuiInput-input']"));
searchbox.sendKeys("fat1");
WebElement search = driver.findElement(By.xpath(".//*[#class='MuiButtonBase-root MuiIconButton-root']"));
search.click();
List<WebElement> menulist = driver.findElements(By.xpath(".//*[#class='MuiButtonBase-root MuiIconButton-root']"));
System.out.println(menulist.size());
menulist.get(3).click();
WebElement deleteicon = driver.findElement(By.xpath("//ul[#class='MuiList-root MuiMenu-list MuiList-padding']"));
deleteicon.click();
To click on the svg enabled Delete icon you need to use WebDriverWait for the elementToBeClickable() and you can use the following xpath based Locator Strategies:
import java.util.Collections;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementToBeClickable {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\\\WebDrivers\\\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get("http://testingapp.workspez.com/login");
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='field_email']"))).sendKeys("rahul#workspez.com");
driver.findElement(By.xpath("//input[#id='field_password']")).sendKeys("Sujeet#19");
driver.findElement(By.xpath("//span[#class='MuiButton-label' and contains(., 'Log In')]")).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[#class='MuiButton-label' and contains(., 'General Info')]"))).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='MuiInputBase-input MuiInput-input']"))).sendKeys("aa");
driver.findElement(By.xpath("//button[#class='MuiButtonBase-root MuiIconButton-root' and #title='Search']")).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[#class='MuiTableCell-root MuiTableCell-body']//button[#class='MuiButtonBase-root MuiIconButton-root']/span[#class='MuiIconButton-label']"))).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//li[#class='MuiButtonBase-root MuiListItem-root MuiMenuItem-root MuiMenuItem-gutters MuiListItem-gutters MuiListItem-button']/*[name()='svg']"))).click();
}
}
Browser Snapshot:

How to post a facebook status message using java and selenium webdriver

I logged into Facebook. Now from home page or News Feed page I want to type some message in "Share an Update" text area and click on Post.
Tried below locator. Didn't work.
driver.findElement(By.name("xhpc_message_text")).sendkeys("Hello World");
WebDriverWait wait = new WebDriverWait(driver, 5);
Try the below code .. it must work for you..
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Facebook_login {
public static void main(String[] args) throws InterruptedException {
String user_name = "facebook_user_name";
String pwd = "facebook_password";
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys(user_name);
driver.findElement(By.name("pass")).clear();
driver.findElement(By.name("pass")).sendKeys(pwd);
driver.findElement(By.xpath("//input[contains(#value,'Log In')]")).click();
Thread.sleep(10000);
System.out.println("logged in successfully");
WebElement notification = driver.findElement(By.xpath("//a[contains(#action,'cancel')]"));
if(notification.isDisplayed()) {
System.out.println("Notification is present");
notification.click();
}
WebElement status =driver.findElement(By.xpath("//textarea[#name='xhpc_message']"));
status.sendKeys("Hello");
Thread.sleep(3000);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Post']"))).click();
}
}
I have found a solution for your question. Please try the below code:
Code:
url = "http://facebook.com";
String email = "email";
String password = "password";
System.setProperty("webdriver.chrome.driver", "src/chromedriver 3");
WebDriver driver = new ChromeDriver();
driver.get(url);
driver.manage().window().maximize();
driver.findElement(By.id("email")).sendKeys("your email id");
driver.findElement(By.id("pass")).sendKeys("Your password" + Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver, 500);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//textarea[contains(#title,'Share an update')]")));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//textarea[contains(#title,'Share an update')]")));
driver.findElement(By.xpath("//textarea[contains(#title,'Share an update')]")).click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[#contenteditable='true']")));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#contenteditable='true']")));
driver.findElement(By.xpath("//div[#contenteditable='true']")).sendKeys("Hello World");
Explanation:
First you have to click on the Share an update text box and then send keys on the div element for which content-editable is set as true.

Selenium Java New Tab in Chrome - won't open , keeps opening URL`s in same tab

package javaapplication1;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class JavaApplication1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Aca\\desktop\\chromedriver.exe");
// Initialize driver
WebDriver driver = new ChromeDriver();
//Maximize browser window
driver.manage().window().maximize();
//Go to URL
driver.get("http://www.google.com");
//Set timeout
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Open new tab – May be you are stuck here
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
//Go to URL
driver.get("http://www.gmail.com");
//Set new tab timeout
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
I am trying to open a new tab, leaving the previous tab opened ..
I can't get a new tab opened. It keeps opening URL`s in the same tab.. I also tried using Actions.
You need to switch the driver to the new tab. In Chrome its done like switching windows
String tabHandle = driver.getWindowHandle();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// switch to the new window
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(tabHandle))
{
driver.switchTo().window(handle);
}
}
driver.get("http://www.gmail.com");
// close the new tab and switch back to the old one
driver.close();
driver.switchTo().window(tabHandle);
As a side note, implicitlyWait is defined for the driver, not tab/window. No need to define it again after opening the new tab.
This is an issue with chromedriver itself. See the related bug submitted
Please try this to open new tab in Chrome with Selenium Java.
package com.sample;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class NewWindow {
public static void main (String[] args){
System.setProperty ("webdriver.chrome.driver", "C:\\Chrome Driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-arguments");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
}
}
You are forgetting to change the focus of the driver to the new tab before navigating.
Try this after opening a new tab:
driver.sendKeys(Keys.chord(Keys.CONTROL,"t"));
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); //Get tabs
driver.switchTo().window(tabs.get(1)); //Navigate to new tab
driver.get("http://www.gmail.com"); //Navigate within new tab
driver.close(); //Close the tab when done
driver.switchTo().window(tabs.get(0)); //Navigate to original tab

Categories