How can I accept cookies on a particular site? - java

When writing a basic search test for a job website in Selenium Java, I ma having problems when trying to accept the cookie warning displayed on the site.
The site has 2 cookie notifications, a middle layer and top layer banner that sit on each other.
I would be grateful for any suggestions (I'm new to Selenium Java!) that would allow me to get past this somewhat irritating (but minor) issue.
This is the code I am using to no avail (both cookie banners remains in place):
I have attempted the xpath approach detailed below
import java.util.Arrays;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Keys;
import java.util.concurrent.TimeUnit;
importnet.bytebuddy.agent.builder.AgentBuilder.RedefinitionStrategy.DiscoveryStrategy.Explicit;
//These are being imported from the Selenium package supplied via Project Level Build Path>External Libraries
public class Demo4SeleniumTypeAndClickXPathExperis {
public static void main(String[] args) {
System.setProperty("webdriverchrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.experis.co.uk/");//Browser URL
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//here is the offending item that seems to achieve no result
driver.findElement(By.xpath("//button[#title='Accept Cookies']")).submit();
driver.findElement(By.xpath("//*[#id=\"query\"]")).sendKeys("test or tester or qa");
driver.findElement(By.xpath("//*[#id=\"search\"]/span/div/div[1]/input")).clear();
driver.findElement(By.xpath("//*[#id=\"search\"]/span/div/div[1]/input")).sendKeys("Bristol");
driver.findElement(By.xpath("//*[#id=\"search\"]/span/div/div[1]/input")).sendKeys(Keys.RETURN);
driver.findElement(By.xpath("//*[#id=\"search\"]/span/div/div[1]/input")).submit();
driver.findElement(By.xpath("//*[#id=\"search\"]/span/div/div[1]/input")).submit();
//driver.close();
}
private static Object navigate() {
// TODO Auto-generated method stub
return null;
I am expecting to be able to accept the cookie banners and clear them from the screen

Use below code to accept both the cookies alert.
I've tested the code on the you URL you provided in your code.
By cookies_accept = By.xpath("//*[#title='Accept Cookies']");
By cookies_gotIt = By.xpath("//a[text()='Got it!']");
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();

To get a more specific answer, I recommend posting the HTML page source which includes HTML for the cookie accept button.
In my experience with accepting cookies, you might have to treat the popup as an alert:
driver.switchTo().alert().accept;

package com.selenium_abcd;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class cookiesDelete {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
WebDriver dr = new ChromeDriver();
dr.manage().deleteAllCookies();
dr.manage().deleteCookieNamed("Cookie name");
}
}

Related

How to validate html5 constraint validation message using Selenium-Webdriver and Java [duplicate]

This question already has answers here:
How to handle HTML constraint validation pop-up using Selenium?
(3 answers)
Closed 3 months ago.
How do I validate the following message? The required class has the floating message.:
try the following, but I get the error "no such alert"
package firsttestngpackage;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginBambu {
public String baseUrl = "http://132.148.19.159:8086/panel/#/login";
String driverPath = "H:\\chromedriver.exe";
public WebDriver driver;
#Test
public void IniciarSesion() {
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.get(baseUrl);
WebElement login = driver.findElement(By.cssSelector("#page-top > div.margen-panel-60.ng-scope > div > div.row.container-fluid.ng-scope > div:nth-child(1) > div > form > button"));
login.click();
String mensaje=driver.switchTo().alert().getText();
System.out.println(mensaje);
}
}
The HTML5 Constraint validation message is the outcome of Constraint API's element.setCustomValidity() method.
Note: HTML5 Constraint validation doesn't remove the need for validation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad guys trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side.
Solution
To retrieve the text which results out from the element.setCustomValidity() method, you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
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 validationmessage {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("http://132.148.19.159:8086/panel/#/login");
WebElement username = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form-control.ng-pristine.ng-invalid.ng-invalid-required.ng-touched[placeholder='Usuario']")));
System.out.println(username.getAttribute("validationMessage"));
}
}
Console Output:
Please fill out this field.

how to pass more than one web elements to page using phantomjs

I am trying to use phantomjs for testing, I have one login page with obvious two parameters username and password. If i try same code with google url where i have to pass only one element with and say element.submit(); but in my login page i want to pass two elements how to achieve the same ?
here is my code -
import java.io.File;
import java.io.IOException;
import org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
public class PhantomExample {
public PhantomExample() {
System.out.println("this is constructor");
}
#Test
public void verify() {
File src = new File("C:\\Users\\Admin\\Downloads\\Compressed\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
DesiredCapabilities phantomjsCap = new DesiredCapabilities();
phantomjsCap.setJavascriptEnabled(true);
phantomjsCap.setCapability("phantomjs.binary.path", src.getAbsolutePath());
System.out.println("inside the verify method");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
WebDriver driver = new PhantomJSDriver(phantomjsCap);
driver.get("http://localhost:8080/MyApp/Login");
System.out.println(driver.getPageSource());
WebElement el =driver.findElement(By.name("username"));
WebElement elp =driver.findElement(By.name("password"));
el.sendKeys("username");
elp.sendKeys("0");
el.submit();
elp.submit();
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
System.out.println(driver.getPageSource());
File Ss=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(Ss, new File("d:/sample.jpg"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
driver.quit();
}
}
Here i created two separate elements and expecting to get the response, but when i run it in debugger mode it is not executing after line el.submit();
I am quite sure that i am doing this wrong way, but can someone tell me what is the right approach to this and explain how to get response object which server would send after log in ?
Calling the submit() method on an input field submits the whole form (with all input values), so the following line can be deleted:
elp.submit();
If the form has a submit button, then after executing el.submit() login will be done.

How do I open multiple tabs in IE instead of multiple windows using Selenium

I am using selenium Java. I need to open Multiple tabs and open different URL's in the newly opened tab. I am try to using getWindowHandles(), It is not working for Internet Explorer. Please suggest the proper solution for this.
Here is the code I have used:
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Multiple
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.ie.driver","C:\\Selenium\\IEDriverServer.exe");
WebDriver d = new InternetExplorerDriver();
d.get("https://www.google.co.in/");
d.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
d.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//d.switchTo().window(d.getWindowHandles().iterator().next());
ArrayList<String> tabs2 = new ArrayList<String> (d.getWindowHandles());
d.switchTo().window(tabs2.get(1));
d.get("https://www.facebook.com/login");
}
}
Using above code I'm able to open new tab but second URL is not entering.
Can any one give me the perfect solution for this?

How to close pop up in selenium webdriver?

I am trying to close pop up using selenium web driver with java. I have tried different ways, but unable to succeed. Please help me.
package Demo;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class YahooTest {
public static void main(String[] args) throws InterruptedException {
FirefoxDriver obj = new FirefoxDriver();
String url = "https://www.planyourjourney.com/";
obj.get(url);
obj.manage().window().maximize();
obj.findElement(By.xpath("html/body/div[12]/div/div/div[9]")).click();
obj.findElementByClassName("dyna-link-new-registration").click();
obj.findElement(By.linkText("B2B Login")).click();
Thread.sleep(4000);
obj.findElement(By.id("userid")).clear();
obj.findElement(By.id("userid")).sendKeys("1592jet#gmail.com");
obj.findElement(By.id("ulPassword")).clear();
obj.findElement(By.id("ulPassword")).sendKeys("spyj01");
obj.findElement(By.name("Next")).click();
Thread.sleep(2000);
obj.findElement(By.id("affilitetrainadvpage"));
Alert alert = obj.switchTo().alert();
alert.dismiss();
}
}
I have seen the source code of the web page and could not find any alert in it.
The pop-up is actually written inside a div tag.
Hence, remove the codes related to alert and use below code which uses xpath.
obj.findElement(By.xpath("//*[#id='affilitetrainadvpage']/span/a/img")).click();

automatic login to gmail error occuring through firefox

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Login {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("https://www.mail.google.com");
driver.findElement(By.id("Email")).sendKeys("abc#gmail.com");
driver.findElement(By.id("Passwd")).sendKeys("xyz");
driver.findElement(By.id("signIn")).click();
}
}
I am trying to write a program to login automatically into gmail.
I have tried everything
please help!!!!
This is giving me the error like this:
Exception in thread "main" java.lang.NoSuchMethodError:com.google.common.
base.Platform.precomputeCharMatcher
(Lcom/google/common/base/CharMatcher;)
Lcom/google/common/base/CharMatcher;
at com.google.common.base.CharMatcher.precomputed(CharMatcher.java:664)
at com.google.common.base.CharMatcher.(CharMatcher.java:71)
at com.google.common.base.Splitter.on(Splitter.java:127)
at org.openqa.selenium.remote.http.JsonHttpCommandCodec.
(JsonHttpCommandCodec.java:59)
at org.openqa.selenium.remote.HttpCommandExecutor.
(HttpCommandExecutor.java:85)
at org.openqa.selenium.remote.HttpCommandExecutor.
(HttpCommandExecutor.java:70)
at org.openqa.selenium.remote.HttpCommandExecutor.
(HttpCommandExecutor.java:58)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.
start(NewProfileExtensionConnection.java:87)
at org.openqa.selenium.firefox.FirefoxDriver.startClient
(FirefoxDriver.java:271)
at org.openqa.selenium.remote.RemoteWebDriver.
(RemoteWebDriver.java:119)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:218)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:211)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:207)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:120)
at com.st.Login.main(Login.java:17)
First of all: that URL doesn't go anywhere (at least in my side). You can achieve what you want as follows:
driver.get("https://accounts.google.com/")
driver.findElement(By.id("Email")).sendKeys("");
driver.findElement(By.id("next")).click();
driver.findElement(By.id("Passwd")).sendKeys("");
driver.findElement(By.id("signIn")).click();

Categories

Resources