Selenium Force Close Firefox - selenium

ProfilesIni profile = new ProfilesIni();
FirefoxProfile ff = profile.getProfile("ScreenCapture");
WebDriver driver = new FirefoxDriver(ff);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get(url);
Thread.sleep(8000);
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
driver.quit();
Shouldn't driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); force a close of the selenium generated Firefox browser after 15 seconds? The browser just sits and says its transferring data for an hour+. Basically just hangs saying its transferring...
I am capturing ajax heavy pages which is why Im asking everything to wait for 8 seconds after page loads. But that should have nothing to do with the driver forcing a close after 15 seconds.
Where am I going wrong?
Details: Centos x64 6.4 with Firefox 10.0.12 and latest Selenium as of 10 min ago.
Is there something I can do in Java to go around this?
Question: How can I force close the Selenium generated Firefox window after N seconds?

If you use Junit along with Java, then some thing like this :-
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
Note :-
To get a full skeleton of how it should be written just download the selenium IDE for FF and export some test case to Java /jUnit.

My linux knowledge is limited, but you can kill a process by running the linux command pkill.
driver.quit();
Thread.sleep(15000); //use a poll loop instead to check process running every 1 sec
Runtime rt = Runtime.getRuntime();
rt.exec("pkill firefox");
I think that the java process will need to have enough permissions to kill a process, but haven't tried it.

To follow up on Ardesco's comment, an example would look as follows:
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ff = profile.getProfile("ScreenCapture");
WebDriver driver = new FirefoxDriver(ff);
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
try {
driver.get(url);
} catch (TimeoutException e) {
System.out.println("15 seconds were over, force continue!");
} finally {
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
driver.quit();
}
The try part will run the request but when the timeout time set with pageLoadTimeout has been exceeded an exception is thrown which we catch. The finally part will be run regardless if the requested page was loaded properly in less than 15 seconds or whether an exception was thrown.

Implicit waits will not force a close of a browser after 15 seconds.
Implicit waits are used when trying to find elements in the DOM, they are not used when trying to load a page. If you want Selenium to stop trying to load a page after 15 seconds you will need to set a pageLoadTimeout, it's used like this:
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
The default page load timeout is 0 (which means wait indefinitely), hence the behaviour that you are seeing.
(There is obviously an assumption here that the driver binary you are using has implemented this method.)
The JavaDoc for timeouts in Selenium is available Here

Related

Link Click using selenium webdriver is giving timeout error, link is working fine on browser otherwise

I'm trying to write a piece of code using Testng in selenium, the problem is when i try to click a link, the code becomes unresponsive and gives error- Timed out receiving message from renderer
Tried driver.get("https://infostore.saiglobal.com/") instead of driver.findElement(By.linkText("Infostore")).click(); still remains unresponsive - Doesnot get directed to the webpage - https://infostore.saiglobal.com/
#Test
public void testSai() throws Exception {
driver.get("https://www.saiglobal.com/"); //open homepage
driver.findElement(By.id("CybotCookiebotDialogBodyButtonAccept")).click(); //accept cookie
driver.findElement(By.cssSelector("#sai-header > div > div.main-nav > div.store-box > div")).click(); //click on Login to open list
sleep(2);
driver.findElement(By.linkText("Infostore")).click(); //click on infostore to be redirected to https://infostore.saiglobal.com/
System.out.println(driver.getCurrentUrl());
Yes I have checked this issue and there is an workaround for this issue if you wish to have this.Try following code.
Take the href attribute value from the link element.
Delete all cookies.
driver.navigate().to(URL);
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + File.separator + "\\Executables\\Chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
Actions actions = new Actions(driver);
driver.get("https://www.saiglobal.com/");
driver.findElement(By.id("CybotCookiebotDialogBodyButtonAccept")).click();
WebElement element=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='desktop-login']")));
actions.moveToElement(element).build().perform();
WebElement element1=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='desktop-login']/ul/li/a[contains(text(),'Infostore')]")));
String str1=element1.getAttribute("href");
driver.manage().deleteAllCookies();
driver.navigate().to(str1);
System.out.println(driver.getCurrentUrl());
}
This seems to be an error with Selenium that the developers have been dealing with for over a year. They never really give a concrete answer as to what causes it or how to fix it.
The first port of call would be to make sure that your browser and Selenium are compatible. Try opening a different URL that you know works, and if the error persists then there is likely an error with the compatibility of your selenium and web browser. If it works, then there is something wrong with your website.
For reference, I opened your website using Python Selenium, and had no issues loading or interacting with elements. So the error is local to the software you are using.
The issue can also be caused by sleeps(no idea why), so try removing any sleeps and see if this stops the issue.

pageLoadTimeout is not working in Selenium - Java

I am testing a website in linux host.The page i am accessing loads infinitely so I am trying to set pageLoadTimeout for selenium.
Firefox is triggered correctly but URL is not loading/navigating/added in url bar.just blank firefox window.I am not seeing any errors also.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
driver.get("http://www.example.com");
However if I remove driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS); code is working fine
Selenium version : 3.14.0;
gecko driver : 18 - linux (tested with gecko 16,17 also same issue)
browser : firefox-52
os/platform : linux
If this kind of some issue how do I make sure my driver quit itself after 5 minute.Host will support only firefox 52.
I checked this link but doesnt fix my problem.
Thanks
Jk
You can set the pageload strategy for browser which will then make the page not wait for the full page load for your other Selenium commands to be executed. Below is the sample code snippet in Java. There are three supported values:
normal
This stategy causes Selenium to wait for the full page loading (html content and subresources downloaded and parsed).
eager
This stategy causes Selenium to wait for the DOMContentLoaded event (html content downloaded and parsed only).
none
This strategy causes Selenium to return immediately after the initial page content is fully received (html content downloaded).
By default, when Selenium loads a page, it follows the normal pageLoadStrategy.
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("pageLoadStrategy", "eager");
FirefoxOptions opt = new FirefoxOptions();
opt.merge(caps);
WebDriver driver = new FirefoxDriver(opt);
driver.get("https://www.google.com/");
If you are interested only in the HTML of the page, better use the "eager" strategy.
You haven't mentioned the url you are trying to access but pageLoadTimeout for Selenium works as expected with With Selenium v3.14.0, GeckoDriver v0.23.0 and Firefox Quantum v62.0.3 combination. I am able to see the expected output on the console with the following example which prints TimeoutException occurred. Quiting the program whenever the pageLoadTimeout is triggered:
Code Block:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class A_Firefox_Test
{
public static void main(String[] args)
{
System.setProperty("god.bless.us", "C:/Utility/BrowserDrivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
driver.get("https://www.booking.com/hotel/in/the-taj-mahal-palace-tower.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaGyIAQGYATG4AQbIAQzYAQHoAQH4AQKSAgF5qAID;sid=338ad58d8e83c71e6aa78c67a2996616;dest_id=-2092174;dest_type=city;dist=0;group_adults=2;hip_dst=1;hpos=1;room1=A%2CA;sb_price_type=total;srfid=ccd41231d2f37b82d695970f081412152a59586aX1;srpvid=c71751e539ea01ce;type=total;ucfs=1&#hotelTmpl");
} catch (TimeoutException e) {
System.out.println("TimeoutException occurred. Quiting the program.");
}
driver.quit();
}
}
Console Output:
1539157195615 Marionette INFO Listening on port 1920
Oct 10, 2018 1:09:56 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Oct 10, 2018 1:10:00 PM org.openqa.selenium.remote.ErrorCodes toStatus
INFO: HTTP Status: '500' -> incorrect JSON status mapping for 'timeout' (408 expected)
TimeoutException occurred. Quiting the program.
You can find the detailed stack trace in pageLoadTimeout in Selenium not working
You can find the Pythonic approach to pageLoadTimeout in How to set the timeout of 'driver.get' for python selenium 3.8.0?

Cross browser test

I have to do login to an application with two different browsers (IE & FF) and hence I tried to do cross browser test. When the URL gets passed to IE, I am getting link as "Continue to this website not recommended", whereas the same link will not be displayed in FF. In the below if I use this statement driver.findElement(By.id("overridelink")).click(); then it works fine in IE but failing in firefox since there wont be any link in FF.
please let me know the possible where one script should run in both the browsers. Below is the script which am trying
#Test
#Parameters("browser")
public void verifypagetitle(String browsername) {
if(browsername.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver",
"D:\\2.53.1\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else if (browsername.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.firefox.bin",
"C:\\Program Files\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
}
driver.get("URL");
driver.manage().window().maximize();
driver.findElement(By.id("overridelink")).click();
driver.findElement(By.id("j_username")).sendKeys("userid");
driver.findElement(By.id("j_password")).sendKeys("pwd");
driver.findElement(By.id("j_password")).submit();
This is most likely caused by the IE security level. In my experience if I change it to Low, the warning is not present. You can try and see if this will solve the issue in your case.
Another solution is to add conditional logic to check the browser being used. Something like this:
Capabilities cap = ((RemoteWebDriver) browserDriver).getCapabilities();
String browsername = cap.getBrowserName();
// This block to find out if it is IE
if ("internet explorer".equalsIgnoreCase(browsername)) {
driver.findElement(By.id("overridelink")).click();
}

driver.close() method is not working in Selenium WebDriver on Firefox

I am writing a simple program in Eclipse using JUnit annotation.
diver.close() is not closing my Firefox browser after the tests. It works fine with Chrome. Code snippet is here.
public class FireFox1 {
WebDriver driver;
#Before
public void setUp() {
driver= new FirefoxDriver();
driver.get("http://book.theautomatedtester.co.uk/chapter4");
}
#After
public void tearDown() {
driver.close();
}
#Test
public void testExamples() {
WebElement element= driver.findElement(By.id("nextBid"));
element.sendKeys("100");
}
}
sometimes while on repeated usages,we'll facing problems with driver.close().
Anyways driver.quit() will rectify your problem.
Generally driver.close() closes the browser(the instance of driver is still intact) and driver.quit() is to kill the webdriver instance. As anyhow you are using here for only one page,then you can go with driver.quit().
Thank you.
Better use driver.quit() method. It closes the browser, but due to some unknown issues it throws NullPointerException. Just catch it..
try{
driver.quit();
}catch (Exception e){
System.out.println("Nothing to do with it");
}
Assuming you have started 5 browsers(classes) parallely using grid:
driver.close - Used for close the current browser( where execution going on)
driver.quit - Used for close all the browsers started by the current execution.
You can use any one of this..
May be browser compatiblity issue, try to downgrade the FF let we see...
Use latest GeckoDriver.exe (17) with Latest FireFox (54.0);
It works fine for me. I had the same problem before.
This problem that you are facing is completely a compatibility problem between driver & Browser version.
driver.close(); should have work without problem if you use above versions. Let me know if it works.
This is what the problem in Firefox driver.close() works in Firefox only with internet connection but in case of Chrome it works without internet connection.

How to stop page load in Selenium Webdriver

I have logged into an account on one of the websites. After login, a click on a button presents that page, but the page keeps on loading without displaying the next page.
What I wanted is, if the page keeps on loading without giving any response for some time, I need to stop the execution of the script.
I have tried by using the below code, but it didn't work
driver.manage().timeouts().pageLoadTimeout(500, TimeUnit.MILLISECONDS);
If you are using firefox, use firefox profile with selenium and set network.http.connection-timeout to seconds (for ex I am setting it to 10 secs) -
In Java,
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.http.connection-timeout", 10);
For stopping the page-load you can use this
public void stopPageLoading() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return window.stop");
}