java Selenium driver.quit() is ignored - java

So I'm trying to learn how to use Selenium, and I found a tutorial on the internet on how to do it (http://toolsqa.com/selenium-webdriver/first-test-case/). I know I am using internet explorer rather than firefox, but I've followed the instructions on how to setup the IEDriver. The problem is that when I use their code to simply open and close a window, it opens it, and ignores the driver.quit() that is in there.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class FirstTestCase {
public static void main(String[] args) {
String service = "C:\\Users\\abc\\Documents\\IE Explorer Server\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
InternetExplorerDriver driver = new InternetExplorerDriver();
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
//Wait for 5 Sec
Thread.sleep(5000);
// Close the driver
driver.quit();
System.out.println(",");
}
}
It prints the comma I have set to print after it closes, but it doesn't actually close the browser. Thread.sleep() also gives an error. I've looked for over 3 hours for some kind of fix for this but couldn't find anything.

Try this:
public static void main(String[] args) throws InterruptedException {
String service = "C:\\Users\\abc\\Documents\\IE Explorer Server\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
InternetExplorerDriver driver = new InternetExplorerDriver();
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
//Wait for 5 Sec
Thread.sleep(5000);
// Close the driver
driver.quit();
System.out.println(",");
}

Here is the Answer to your Question:
I don't see any significant error in your code block. A few suggestions about the solution:
I retested your code block with Selenium 3.4.0, IEDriverServer 3.4.0 & MSIE 10.0 with only one additional parameter as
public static void main(String[] args) throws InterruptedException
and your code executes just fine. Whenever you add Thread.sleep(5000); in your code you may consider to add throws InterruptedException. But again, as per best practices we must avoid using Thread.sleep() and replace it by ImplicitlyWait or ExplicitWait.
You have used the InternetExplorerDriver implementation to initiate the driver. As per W3C standards you must consider using the WebDriver interface instead.
As per your comment driver.quit() not only closes the driver but also kills the driver instance and releases the memory.
Here is your own code with some small tweaks which works well at my side:
public static void main(String[] args) throws InterruptedException
{
String service = "C:\\your_directory\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
WebDriver driver = new InternetExplorerDriver();
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Print a Log In message to the screen
System.out.println("Successfully opened the website www.Store.Demoqa.com");
// Quit the driver
driver.quit();
System.out.println(",");
}
Let me know if this Answers your Question

Related

Using DataProvider by initializing WebDriver one time within TestNG

I'm trying to check login page control by using dataprovider but i don't want to initialize webdriver again and again for each username password control. Once i come into login page, checking all concerned scenarios on login page in single time without starting another driver seems more convenient to me but i couldn't figure it out. When running following code, data[0][0] and data[0][1] is being correctly checked but it gives no such element on Login method having second priority test annotation when being tried to be typed data[1][0] and data[1][1]. Probably, it causes because driver is not looking at that page on that time. How can I handle this issue ?
error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class='q-input-wrapper email-input']//input[#class='q-input']"}
code:
public class TestCaseFirst {
public WebDriver driver;
#BeforeTest
public void Start() throws InterruptedException {
WebDriverManager.chromedriver().setup();
driver= new ChromeDriver();
driver.get("https://www.faxzas.com/");
driver.manage().window().maximize();
Thread.sleep(2000);}
#Test(priority=1)
public void RoadtoLogin() throws InterruptedException {
driver.findElement(By.xpath("//a[#title='Close']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='login-container']//span[#id='not-logged-in-container']")).click();;
Thread.sleep(1000);
}
#Test(dataProvider="loginInfos", priority=2)
public void Login(String mail, String password) throws InterruptedException {
driver.findElement(By.xpath("//div[#class='q-input-wrapper email-input']//input[#class='q-input']")).sendKeys(mail);
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='q-input-wrapper']//input[#class='q-input']")).sendKeys(password);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#type='submit']")).click();
Thread.sleep(1000);
String description = driver.findElement(By.xpath("//div[#id='error-box-wrapper']//span[#class='message']")).getText();
System.out.println(description);
}
#DataProvider(name="loginInfos")
public Object[][] getData(){
Object[][] data = new Object[6][2];
data[0][0]="blackkfredo#gmail.com";
data[0][1]="";
data[1][0]="blackkfredo#gmail.com";
data[1][1]="443242";
data[2][0]="";
data[2][1]="1a2b3c4d";
data[3][0]="";
data[3][1]="";
data[4][0]="blackkfredogmail.com";
data[4][1]="1a2b3c4d";
data[5][0]="blackkfredo#gmail.com";
data[5][1]="1a2b3c4d";
return data;
}
}
You need to reset your page to the login page where you are expecting the element to be. Either put an #AfterMethod and go back to the page you are trying to test or put an #BeforeMethod for the same. You may even want to wrap up your find element calls and handle the exceptions by going back to the main page.

How to quit appium driver and run another test without Session ID is null error

I use BrowserStack. Before each test I create new driver. After each scenario I use driver.quit() because I want to close the session.
When I have more than one test case (e.g two scenario files) to run I get a message Session ID is null. Using WebDriver after calling quit()?.
When I don't use driver.quit() or I use driver.closeApp(), the first session takes too long and even if the second one starts, I cannot use it (I mean I cannot click on elements). I run my tests by junit runners.
Is there any possibility to quit driver after each test and run another one without that error?
private static AppiumDriver<MobileElement> driver;
#Before
public void before() {
driver = new AndroidDriver<>(new URL("URL"), capabilities);
}
public static AndroidDriver<MobileElement> getDriver() {
return (AndroidDriver<MobileElement>) driver;
}
#After
public void after() {
if ( driver == null ) {
driver.quit();
driver = null;
}
}
If you are facing this issue, please go through the BrowserStack documentation for the Junit demo code here, this is will help you solve the issue.
I can see your code mentioned "Before" & "After" only not "BeforeEach" / "AfterEach".
Please try this out

How to quit the page if i type hello world on google search using selenium?

Hi guys I want to quit the page afte I type "Hello World" in google search using firefox browser and selenium
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.quitPage();
}
private void openBrowser() {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
driver = new FirefoxDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
1) Create a Junit test class
2) Initialize the driver in your setup method like
ChromeDriver driver = new ChromeDriver();//Download chromeDriver.exe file and point to location where you have installed the like as you mentioned. `driver.System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");`
3) Create a test method with your business logic to type hello world
3) Create After and Before Class annotations for the methods .In After class annotation method you can write driver.quit.
You can refer to following link for more clarity
https://www.guru99.com/selenium-tutorial.html
I am Added sample format which is written Using java and testNG..Here Every time First before method will run then 1st test case will execute then after method will work then again before method work then next test case......In this way you can manage your test case and it will also generate Report also.Here you will get better explanation.
public class GoogleTest {
FirefoxDriver driver;
#BeforeMethod
public void setUp1() throws Exception {
System.setProperty("webdriver.gecko.driver", "D:\\\\ToolsQA\\trunk\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void GoogleInputField() throws InterruptedException {
System.out.println("Hello world");
System.out.println("Hello world");
//Write Your test case for test case 1
}
#Test
public void google suggestion() throws InterruptedException {
//Write Your test case for test case 1
}
#AfterMethod
public void getResult(ITestResult result) throws IOException {
driver.quit();
}
}
Dont forget to add Firefox driver on gecko.driver path
I am assuming that you want to open the browser using selenium, load google and then listen till you MANUALLY enter "hello world" in the input box. The method listenForHelloWorld() will do that.
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void listenForHelloWorld() {
// Get the search field
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
// if search field value is "hellwo world" break loop which will eventallu lead to `quit()` as it is the next method to exit.
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
Thread.sleep(5000)
}
}
If you are asking how to enter "hello world" in browser automatically use below.
driver.findElement(By.name("q")).sendKeys("hello world");

Selenium webdriver. Endless page loading

I use Selenium webdriver with Firefox for scraping web pages. Sometimes web browser waits endless time for some excessive requests complete (e.g. to facebook.net).
I've tried to use BrowserMob-Proxy to filter these requests. But it didn't help. These requests, even after receiving 200 or 404 code, doesn't stop.
I thought about some possibility to stop web browser loads page after some amount of time.
For example:
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt(); }
((JavascriptExecutor) driver).executeScript("window.stop();");
But it doesn't work until web page loads completely.
What can you suggest me to do in my case?
P.S. This is a code with using a pageLoadTimeout parameter.
WebDriver driver;
FirefoxBinary firefox;
FirefoxProfile customProfile;
public static void main(String[] args) {
openFirefox();
for (String url : listOfUrls) {
Boolean pageLoaded = false;
while (pageLoaded == false) {
try {
driver.get(url);
pageLoaded = true;
} catch (org.openqa.selenium.TimeoutException ex) {
System.out.println("Got TimeoutException on page load. Restarting browser...");
restartFirefox();
}
}
//here I do something with a content of a webpage
}
}
public static void openFirefox(){
firefox = new FirefoxBinary(new File(Constants.PATH_TO_FIREFOX_EXE));
customProfile = new FirefoxProfile();
customProfile.setAcceptUntrustedCertificates(true);
customProfile.setPreference("webdriver.load.strategy", "unstable");
driver = new FirefoxDriver(firefox, customProfile);
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
private static void restartFirefox() {
driver.close();
firefox.quit();
openFirefox();
}
How about using timeouts? So for each WebDriver instance that you are using you need to set:
WebDriver.Timeouts pageLoadTimeout(long time, java.util.concurrent.TimeUnit unit)
Which by the Documentation:
Sets the amount of time to wait for a page load to complete before
throwing an error. If the timeout is negative, page loads can be
indefinite.
Parameters:
time - The timeout value.
unit - The unit of time. Returns:
A Timeouts interface.
I've tried to use BrowserMob-Proxy to filter these requests. But it
didn't help. These requests, even after receiving 200 or 404 code,
doesn't stop.
What do you mean "didn't help". I don't believe you. Please share your code for blacklisting URLs. For example, following code code returned HTTP.200 for any google-analytics related site for me
server.blacklistRequests("https?://.*\\.google-analytics\\.com/.*", 200); // server is bmp proxy server
I have heard, that WebDriver should now have webdriver.load.strategy. I have never used it though. So the default behavior of WebDrivers blocking calls (a'la get()) is to wait for document.readyState to be complete, but I have read that with this property you could tell the driver to return at once. So might be worth googling it for a while.

Selenium web driver not able to close firefox instance if a Test cases is failed

i folks,
i am using junit with selenium web driver 2.28.
the problem is if i run a successful test case the web drives is able to close the firefox instance, but when a test case fails the selenium web driver is not able to close the firefox.
i am using FF 15.0.1 with selenium-server-standalone-2.28.0.jar.
please respond
thanks
Sahil
private void startWebdriver() throws UIException{
//2) Prevent re-use.
if(UIHandlerWD.this.profile == null)
throw new
UIException(
UIException.Code.UI,
"Webdriver instance cannot be instantiated."
);
//3) Configure Selenium Webdriver.
if (this.profile.browserType.equalsIgnoreCase("*firefox")){
FirefoxProfile fProfile = new FirefoxProfile();
// profile.SetPreference("network.http.phishy-userpass-length", 255);
fProfile.setAcceptUntrustedCertificates(true);
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setJavascriptEnabled(true);
dc.setCapability(FirefoxDriver.PROFILE, fProfile);
//this.webdriver = new FirefoxDriver(dc);
this.webdriver = new FirefoxDriver(dc);
}
else if (this.profile.browserType=="INTERNETEXPLORER")
this.webdriver = new InternetExplorerDriver();
else
throw new
UIException(
UIException.Code.UI,
"Unknown browser type '" + this.profile.browserType +"'."
);
//4) Start Webdriver.
this.webdriver.get(this.profile.getURL().toString());
this.webdriver.manage().timeouts().
implicitlyWait(5, TimeUnit.SECONDS);
this.webdriver.manage().timeouts().
pageLoadTimeout(this.profile.timeout, TimeUnit.SECONDS);
}
void stopWebdriver() {
if(this.webdriver != null){
try{
Thread.sleep(5000);
}
catch (Exception e) {
// TODO: handle exception
}
this.webdriver.close();
}
this.webdriver = null;
this.profile = null;
}
Add webdriver.quit() to an #AfterClass method.
close() will shut the current active window. If the current active window is the last window it is functionally equivalent to performing a quit().
It does however need to have a valid active session to be able to do this. If your test has failed that session is probably dead, so when you call a close() it doesn't know where to send the command and throws an Exception.
quit() will end all sessions and shut down all clients, it's basically a clean up everything command. It will also not throw any Exceptions if all clients/sessions have already been closed/ended.

Categories

Resources