I can’t close a pop-up on the flipkart web-site - java

I was trying to learn Selenium , i used flipkart site to automate , but when i redirect to flipkart i cant able to close a pop up
I used the 'x' button by its xpath & classname but its not working
[img]https://i.ibb.co/7bhDJYw/Screenshot-2022-11-29-at-10-31-19-AM.png[/img]
package ui;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Popup {
public static String browser = "Firefox";
public static FirefoxDriver driver;
public static void main(String args[]) throws InterruptedException {
if (browser.equals("Firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if (browser.equals("Chrome")) {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
} else if (browser.equals("Edge")) {
WebDriverManager.edgedriver().setup();
EdgeDriver driver = new EdgeDriver();
}
driver.manage().window().maximize();
driver.get("https://www.flipkart.com/");
// Thread.sleep(5000);
// driver.findElement(By.className("_2KpZ6l _2doB4z")).click();
Thread.sleep(2000);
// Alert alert = (Alert) driver.switchTo().alert();
// alert.dismiss();
}
}
this is the code i tried

Instead of doing this
driver.findElement(By.className("_2KpZ6l _2doB4z")).click();
do this
driver.findElement(By.xpath("//button[contains(text(),'✕')]")).click();
or
driver.findElement(By.cssSelector("._2KpZ6l._2doB4z")).click();

Related

How to resolve this "NET::ERR_CERT_COMMON_NAME_INVALID" exception in Selenium Java?

I'm working on a Java Project using Selenium. I have attempted to implement my test codes. Below here is the snippet of it.
AutoTest
public class AutoTest {
WebDriver driver = null;
#BeforeTest
public void setUp() {
String projectPath = System.getProperty("user.dir");
DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome ();
handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true);
//Configuration for WebDriver
System.setProperty("webdriver.chrome.driver", projectPath+"/drivers/chromedriver/chromedriver.exe");
driver = new ChromeDriver(handlSSLErr);
}
#Test
public void createTopUpRequest() {
//browse to UAT Server
driver.get("https://10.2.5.215:33000/viewTopUpRequest");
//enter credentials
LoginPage.usernameLogin(driver).sendKeys("ezltest2svc");
LoginPage.passwordLogin(driver).sendKeys("Password123!");
//Click on submit button
LoginPage.loginButton(driver).sendKeys(Keys.RETURN);
}
#AfterTest
public void closeBrowser() {
//driver.close();
}
}
As soon as it tries navigating to this portal: "https://10.2.5.215:33000/viewTopUpRequest", I get the NET::ERR_CERT_COMMON_NAME_INVALID exception. May I know how to bypass the security protocols?
I'm not sure if org.openqa.selenium.remote.DesiredCapabilities even provides such option.
I'm using org.openqa.selenium.chrome.ChromeOptions:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public static String userDir = System.getProperty("user.dir");
public static String chromedriverPath = userDir + "\\resources\\chromedriver.exe";
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return driver;
}
This works as well:
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return driver;
}
Tested on https://badssl.com/

Chrome doesn't open URL automatically

Why did this happen? Chrome opens but the URL does not open with the code.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Id {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\chromedriver\\chromedriver.exe"); //open browser
WebDriver driver = new ChromeDriver();
**driver.get("google.co.in"); //open URL**
driver.findElement(By.name("q")).sendKeys("Quadkast" + Keys.ENTER);
}
}
You need to give http/https protocol along with the url in the get() method
driver.get("http://www.google.com");
or
driver.get("https://google.com");

NullPointerException in Selenium WebDriver

I'm a beginner Selenium practitioner. I have 2 classes, one for the WebDriver another is for Log In. I followed some youtube tutorials but can't pinpoint what I'm doing wrong. I tried the concept of 'Baseclass' where I extend the other class.
LogIn Class
WebDriver Class
If I add the WebDriver in the other class, it will run successfully. But I want to make it more 'organized'
this is the error
Error message
public Webdriver driver;
Please add static in this line
public static Webdriver driver;
because you need use same driver instance for all classes
create above line in top of both classes
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;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class TestApp {
private WebDriver driver;
private static TestApp myObj;
// public static WebDriver driver;
utils.PropertyFileReader property = new PropertyFileReader();
public static TestApp getInstance() {
if (myObj == null) {
myObj = new TestApp();
return myObj;
} else {
return myObj;
}
}
//get the selenium driver
public WebDriver getDriver()
{
return driver;
}
//when selenium opens the browsers it will automatically set the web driver
private void setDriver(WebDriver driver) {
this.driver = driver;
}
public static void setMyObj(TestApp myObj) {
TestApp.myObj = myObj;
}
public void openBrowser() {
//String chromeDriverPath = property.getProperty("config", "chrome.driver.path");
//String chromeDriverPath = property.getProperty("config", getChromeDriverFilePath());
System.setProperty("webdriver.chrome.driver", getChromeDriverFilePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void navigateToURL() {
String url =property.getProperty("config","url");
;
driver.get(url);
}
public void closeBrowser()
{
driver.quit();
}
public WebElement waitForElement(By locator, int timeout)
{
WebElement element = new WebDriverWait(TestApp.getInstance().getDriver(), timeout).until
(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private String getChromeDriverFilePath()
{
// checking resources file for chrome driver in side main resources
URL res = getClass().getClassLoader().getResource("chromedriver.exe");
File file = null;
try {
file = Paths.get(res.toURI()).toFile();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
}
//create package name called utils and under that package create class name with TestApp and paste above code
if you want use driver anywhere in your project
TestApp.getInstance().getdriver();
You didn't initialize your driver anywhere.
You need to use a before
#BeforeClass
public void setupClass(){
driver = new Chromedriver();
}
and in opensite
public static WebDriver driver;
You want your OpenSite class to act as the base class which you can extend it to your test class to intialize your driver. Remove your "#test" annotaion from the OpenSite class.
Add static with "public WebDriver driver";
Create a method openBrowser(already there) or driverInitialization in this class.
Return the driver instance.
Updated code will look like
public class OpenSite{
public static WebDriver driver;
public static void openBrowser(){
System.setProperty("webdriver","path");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("your URL");
return driver;
}
}
And in test class LogIn extend this class and call this method:
public class LogIn extends OpenSite{
#BeforeTest
public void driver initialization(){
openBrowser();
}
#Test
public void logInVendor(){
//Write your code here
}
}

getWindowHandles() not working in firefox 58.The focus remains on parent tab and does not transfer to next tab

I am starting to learn how to handle multiple tabs in a browser using Selenium with Java. looks like my code below is not working.
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static void main(String[] args) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
//Get Data Policy
WebElement we= driver.findElement(By.linkText("Data Policy"));
//Click Data Policy link
we.click();
//Create an arrayList
ArrayList<String> s1= new ArrayList<String>(driver.getWindowHandles());
for(String s2:s1)
{
if(!(s2.equalsIgnoreCase(parent)))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
}
}
Please let me know how can I display the title 'Data Policy' without using
getWindowHandles().
getWindowHandles() works pretty fine but before invoking getWindowHandles() you have to induce WebDriverwait as follows :
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
driver.findElement(By.linkText("Data Policy")).click();
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> s1= driver.getWindowHandles();
for(String s2:s1)
{
if(!parent.equalsIgnoreCase(s2))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
Console Output :
Parent Window is4294967297
4294967303
get title of windowData Policy
Just put Thread.sleep(3000); after clicking on Data Policy link.
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
//D:\new folde backup\Selenium_project\seleniumproject\testNG_practice\driver
System.setProperty("webdriver.gecko.driver", "./driver/geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent = driver.getWindowHandle();
System.out.println("Parent Window is" + parent);
// Get Data Policy
WebElement we = driver.findElement(By.linkText("Data Policy"));
// Click Data Policy link
we.click();
// Create an arrayList
Thread.sleep(3000);
ArrayList<String> s1 = new ArrayList<String>(driver.getWindowHandles());
System.out.println(s1);
for (String s2 : s1) {
if (!(s2.equalsIgnoreCase(parent))) {
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window" + driver.getTitle());
}
}
}
}
Output:-
Parent Window is4294967297
[4294967297, 4294967301]
4294967301
get title of windowData Policy

How to handle same multiple windows e.g. google in Selenium WebDriver with Java

I have used the code below trying to open same multiple window "Google". Kindly help me in editing this and explaining how to handle this .
driver.switchTo().window("gbar");//not sure how to use this
and below code tried in Selenium:
package Testing;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.*;
public class Float {
public static void setUp() {
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
}
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.name("q"));
element.click();
WebDriverWait wait = new WebDriverWait(driver, 80);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("q")));
element.sendKeys("hi");
element.clear();
Thread.sleep(2000);
element.sendKeys("hey");
element.submit();
setUp();
driver.switchTo().window("gbar");// //* not sure how to use this *///
WebElement element1 = driver.findElement(By.name("q"));
element1.click();
element1.sendKeys("hi");
element1.clear();
element1.sendKeys("hey");
element1.submit();
driver.quit();
}
}
You can get a handle to your window via driver.getWindowHandle()and you can switch to a window with driver.switchTo().window("handle");.
If you want to open a new window you can click on a link with target="_blank" on the website or execute JavaScript to open a new window. Then you'll find another handle in driver.getWindowHandles(). A possible way could be:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
List<String> knownHandles = new ArrayList<String>();
knownHandles.add(driver.getWindowHandle());
((JavascriptExecutor)driver).executeScript("window.open();");
// find the new handle. we are getting a set
for (String handle : driver.getWindowHandles()) {
if (!knownHandles.contains(handle)) {
knownHandles.add(handle);
break;
}
}
String newHandle = knownHandles.get(knownHandles.size() -1 );
driver.switchTo().window(newHandle);
driver.get("https://www.google.com");
Another way is to inject the anchor and click it via JavaScript.
//Store the current window handle
String winHandleBefore = driver.getWindowHandle();
//Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
driver.manage().window().maximize();
//Close the new window, if that window no more required
driver.close();
//Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
Here is a sample example handling multiple windows:
public class Mytesting {
WebDriver driver = new FirefoxDriver();
#Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
#Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();
// Get and store both window handles in array
Set<String> AllWindowHandles = driver.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code = "+AllWindowHandles.toArray()[1]);
//Switch to window2(child window) and performing actions on it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[#name='fname']")).sendKeys("My Name");
driver.findElement(By.xpath("//input[#value='Bike']")).click();
driver.findElement(By.xpath("//input[#value='Car']")).click();
driver.findElement(By.xpath("//input[#value='Boat']")).click();
driver.findElement(By.xpath("//input[#value='male']")).click();
Thread.sleep(5000);
//Switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//option[#id='country6']")).click();
driver.findElement(By.xpath("//input[#value='female']")).click();
driver.findElement(By.xpath("//input[#value='Show Me Alert']")).click();
driver.switchTo().alert().accept();
Thread.sleep(5000);
//Once Again switch to window2(child window) and performing actions on it.
driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[#name='fname']")).clear();
driver.findElement(By.xpath("//input[#name='fname']")).sendKeys("Name Changed");
Thread.sleep(5000);
driver.close();
//Once Again switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//input[#value='male']")).click();
Thread.sleep(5000);
}

Categories

Resources