I am starting to learn selenium to switch from manual to automatic testing.
I was following a tutorial on a website. but when I launched the script the first time, and opened the page for the test I discovered this cookie acceptance (sorry if it's in Italian)
After discovering that the advice was inside an iframe I rewrote the script to handle it. My idea was "Now I click on "Accept All" (Accetta tutti) and I can continue with the tutorial." Unfortunately, the click() command doesn't work.
This is my script:
package newpackage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class popUpAutomation {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/ccumi/Downloads/chromeDriver/chromedriver.exe");
WebDriver chrome = new ChromeDriver();
chrome.get("https://demo.guru99.com/popup.php");
chrome.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
int size= chrome.findElements(By.tagName("iframe")).size();
System.out.println("iframe "+ size);
chrome.switchTo().frame(3);
System.out.println(chrome.findElement(By.xpath("//button[@id='save']/span/div")).getText());
chrome.findElement(By.id("save")).click();
}
}
I don't understand where is the error, because on the console I see that in this line the element is found:
System.out.println(chrome.findElement(By.xpath("//button[@id='save']/span/div")).getText());
Refer the working code below with in-line explanation:
chrome.get("https://demo.guru99.com/popup.php");
chrome.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);;
int size= chrome.findElements(By.tagName("iframe")).size();
System.out.println("iframe "+ size);
// switch into the IFRAME with ID=gdpr-consent-notice
chrome.switchTo().frame(chrome.findElement(By.id("gdpr-consent-notice")));
System.out.println(chrome.findElement(By.xpath("//button[@id='save']/span/div")).getText());
// Below 2 lines will click on the Accept All button using JavaScript
WebElement element = chrome.findElement(By.xpath("//button[@id='save']/span/div"));
((JavascriptExecutor) chrome).executeScript("arguments[0].click();", element);
// Below line will come out of the IFRAME and switch to main HTML context
chrome.switchTo().defaultContent();
Console result:
iframe 3
Accept All