Dismissing Firefox Security Warning in Selenium WebDriver? - java

I'm having trouble with the Java Security Warning that pops up for an invalid certificate. I have set up the FireFox profile as such
FirefoxProfile fp = new FirefoxProfile();
fp.setAssumeUntrustedCertificateIssuer(false);
fp.setAcceptUntrustedCertificates(true);
fp.setPreference("security.enable_java",true);
fp.setPreference("plugin.state.java",2);
//New driver
WebDriver driver = new FirefoxDriver(fp);
Although this skips the "Get me out of here" screen I am unable to dismiss the next popop. I have also tried using
driver.switchTo().alert().accept()
but this leads to an exception.

Try this:-
Go to mozilla firefox
Click on Tools -> options
Click on security
Uncheck all checkbox
Close the browser
Now run your script.
FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("browser.safebrowsing.enabled", true);
fp.setPreference("browser.safebrowsing.malware.enabled", true);
WebDriver driver = new FirefoxDriver(profile);
driver.get("http://addonrock.ru/Debugger.js/");
best of luck :)

It could be due to you are not waiting for it appear before executing driver.switchTo().alert().accept()
try following for each alerts
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}

Related

How to handle keyboard operation on selenium chrome browser running on virtual ubuntu 22

I am trying to select "OK" button against my browser certificate pop-up using robot class. The same piece of code works well on windows but failing on ubuntu.
Code:
public void load() {
setUrl();
Thread threadNavigation = new Thread() {
#Override
public void run() {
driver.navigate().to(url);
}
};
Thread threadCertificateHandler = new Thread() {
#Override
public void run() {
try {
Thread.sleep(3000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(2000);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Start the threads.
threadNavigation.start();
threadCertificateHandler.start();
// Wait for them both to finish
try {
threadNavigation.join();
threadCertificateHandler.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Code Explanation: As soon as url is navigated using selenium, a certificate pop-up is displayed before page is loaded. The approach I have used here - 1 thread used here to get application url and another thread is used to handle the pop-up.
Attaching screenshot of the pop-up.
ChromeDriver Init Code:
public void getStandaloneHubNodeServerDriver(String browserType,String platformType, String url) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
logger.log(Level.INFO, () -> "Setting browser address #: " + url);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
options.setAcceptInsecureCerts(true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
//threadLocalDriver.set(new RemoteWebDriver(new URL(url),options));
driver = new RemoteWebDriver(new URL(url),options);
driver.manage().window().maximize();
}
The same code works like a charm on local windows but when executed on remote VM running on linux, it does not perform the "Enter" event. Is there's any alternative to Robot class that can be used for linux?
Robot class is generally inconsistent as it blindly performs keyboard or mouse actions. I have figured out a solution to select the browser certificate without Robot class. This works only on Firefox though. If you are happy to switch from Chrome to Firefox, try the below code:
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-profile");
options.addArguments("C:/Users/username/AppData/Roaming/Mozilla/Firefox/Profiles/zyz.default");
WebDriver driver = new FirefoxDriver(options);
In the above code, driver instance is loaded with the default Firefox browser profile. This profile will contain the certificate which will be accepted automatically and pop-up will not even be triggered. Try this and see if you can get away from using Robot class.

How to quit the driver while waiting in Selenium?

I wonder how to safely quit the driver when the user closes the program while waiting for the element to appear.
`
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
options.addArguments("−−mute−audio");
WebDriver driver = new ChromeDriver(options);
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(Integer.MAX_VALUE));
driver.get(URL);
driver.findElement(By.xpath("/html/body")).click();
while (isAllowed) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class='alert-layout animated fadeIn v-enter-to']")));
//...
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("div[class='alert-layout animated fadeIn v-enter-to']")));
}
LOGGER.info("quit selenium");
driver.quit();
`
I thought it would be solved by making isAllowed false at the end of the program, but it didn't.

Selenium: Page gets refreshed after login

After the code clicks the action to login, the page gets refreshed and doesn't redirect to the next page. This only occurs for this website as I am redirected properly on other sites.
When I am giving the wrong credentials even the error message is not getting displayed.(Manually it works)
I am testing in Chrome with Selenium java.
Here is my code:
public class Test {
private static final String HTMLPageSourceCode = null;
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:\\Selenium project\\chromedriver_win32/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://-----/tandem/login");
Thread.sleep(5000);
driver.manage().deleteAllCookies();
driver.findElement(By.id("login")).sendKeys("----");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.findElement(By.id("password")).sendKeys("----");
WebElement loginbutton = driver.findElement(By.xpath(".//*[#id='login-button']"));
Actions actions = new Actions(driver);
actions.click(loginbutton).perform();
}
}
To login in into the website https://outhouse.inhouseusa.com/tandem/login/ you need to induce WebDriverWait for the elementToBeClickable() and you can use the following Locator Strategies:
Code Block:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
//options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);
driver.get("https://outhouse.inhouseusa.com/tandem/login/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form-control#login"))).sendKeys("sandy");
driver.findElement(By.cssSelector("input.form-control#password")).sendKeys("sandy");
driver.findElement(By.cssSelector("input.pull-right.button.button-primary#login-button")).click();

How to access form type login/registration pop up in Selenium

I am trying to access the following site and get a registration pop up. In HTML it shows as form type. I tried handling as alert but it is not and I get exception as no modal dialog box opened. I tried window handles. The size of the window handles is only 1.
Please help me, so that, I can click on 'Signin' link on registration form and then login.
Website: http://way2automation.com/way2auto_jquery/index.php
System.setProperty("webdriver.gecko.driver", "C:\\mamtha\\Selenium Practice\\GeckoDriver\\geckodriver.exe");
String URL = "http://way2automation.com/way2auto_jquery/tooltip.php";
WebDriver driver = new FirefoxDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thread.sleep(3000);
Set <String> winhandle = driver.getWindowHandles();
System.out.println(winhandle.size());
WebElement sigin = driver.findElement(By.xpath("//a[contains(text(), 'Signin']"));
sigin.click();
driver.findElement(By.xpath("//input[#name = 'username']")).sendKeys("myusername");
driver.findElement(By.xpath("//input[#name = 'password']")).sendKeys("password");
driver.findElement(By.xpath("//input[#class = 'button']")).click();
Modal dialog box is getting opened in the same page itself.so, you don't want to use the window handles. You need to move the focus to the modal dialog box first and then directly access the required element(add some explicit wait condition as well).
Working Code:
System.setProperty("webdriver.gecko.driver", "C:\\mamtha\\Selenium Practice\\GeckoDriver\\geckodriver.exe");
String URL = "http://way2automation.com/way2auto_jquery/tooltip.php";
WebDriver driver = new FirefoxDriver();
driver.get(URL);
driver.manage().window().maximize();
//Explicit wait is added after the Page load
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Welcome"));
WebElement modalDialogBox=driver.findElement(By.className("fancybox-skin"));
modalDialogBox.findElement(By.xpath(".//a[text()='Signin']")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("fancybox-skin")));
WebElement loginDialogBox=driver.findElement(By.className("fancybox-skin"));
loginDialogBox.findElement(By.name("username")).sendKeys("myusername");
loginDialogBox.findElement(By.name("password")).sendKeys("987654321");
loginDialogBox.findElement(By.className("button")).click();
Try the following code.
String URL = "http://way2automation.com/way2auto_jquery/tooltip.php";
WebDriver driver = new ChromeDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
Thread.sleep(5000);
WebElement sign=driver.findElement(By.xpath("//p[#class='text_popup']/a[contains(text(),'Signin')]"));
sign.click();
Thread.sleep(5000);
driver.findElement(By.xpath("//div[#id='login']/form/fieldset[1]/input")).sendKeys("myusername");
Thread.sleep(5000);
driver.findElement(By.xpath("//div[#id='login']/form/fieldset[2]/input")).sendKeys("password");
driver.findElement(By.xpath("//div[#id='login']/form/div/div[2]/input")).click();

Selenium.setTimeout does not wait for specified time

We have to continuously monitor a URL to check for its availability. I have used selenium for simulation. Pasted below is the piece of code.
driver = new InternetExplorerDriver();
selenium = new WebDriverBackedSelenium(driver, mainUrl);
selenium.setTimeout("90000");
selenium.open(mainUrl);
However, selenium.timeout does not work even if the URL does not get opened up in 90000 milliseconds. How can I fix this?
You can also use :
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
According the selenium javadoc, the example looks like this:
driver = new InternetExplorerDriver();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
selenium.open(mainUrl);
try use Thread.sleep():
final String sUrl = "http://www.google.ca/index.html";
// Instantiate the Internet Explorer browser.
WebDriver oWebDriver = new InternetExplorerDriver();
// Open the main google webpage.
oWebDriver.get(sUrl);
try
{
Thread.sleep(5000);
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
If you'd like to check for availability somtheing try also using fluentWait:
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
Hope this helps you)

Categories