Selenium Firefox driver window isn't closed when an exception raises - selenium

So lets assume I have some function using FirefoxDriver:
def init_firefox():
driver = webdriver.Firefox()
...
And during performing this function there might be an exception raised by some reason. I catch it by this way:
try:
init_firefox()
except Exception:
print('Exception raised!')
The issue I've encountered is that when init_firefox really raises an exception, Firefox window isn't closed and persists in RAM. Is there a way to close this single window without closing other ones?

Yes there is a way to close the window you want, The only thing you need in this case is for the driver to be in that specific window to be closed !!
This is a bit explanation on how to do so!!
I tested this code with chromedriver i already have in my machine
# x refers to the window you want to switch to x = 1 or 2 ..
window_to_close = driver.window_handles[x]
driver.switch_to.window(window_to_close)
driver.close()

Related

Selenium Alert behavior

Which of the following statements is TRUE when an alert is open in a browser? (Assume that
driver is a WebDriver object)
I. driver.findElements throws an exception
II. driver.close throws an exception
III. driver.close closes the current window.
IV. driver.findElements returns an empty list.
☐ (a) I, II.
☐ (b) I, III.
☐ (c) II, III.
☐ (d) III, IV.
My answer would be D(III and IV) as I know driver.findElements doesn't throws the exception and only returns the empty list when it doesn't able to find an element(https://www.softwaretestingmaterial.com/difference-between-findelement-and-findelements-methods/#:~:text=findElements%20method%20returns%20the%20list,t%20exist%20on%20the%20page.)
Your thoughts please. i found the answer as below
Answer B is correct
• In this case driver.findElements method would throw an exception, however
driver.close would close the window as expected. can someone explain this for me
driver.findElements
driver.close
Albeit Option D (III and IV) is the correct answer as:
close() closes the current window, quitting the browser if it's the last window currently open.
findElements() find all elements within the current page using the given By mechanism. This method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.

Selenium hanging with xvfb

I am attempting to run automated selenium headless tests, and I'm running into the issue where the tests hang for some inexplicable reason. The full snippet is on pastebin, but the relevant portion of the code is reproduced below:
# stress testing
i = 0
while True:
print i
d = webdriver.Remote(
service.service_url,
desired_capabilities=DesiredCapabilities.CHROME
)
print i, "started driver"
d.get("http://www.facebook.com")
print i, "got fb"
d.quit()
print i, "quit"
i += 1
Sample output is
0
0 started driver
0 got fb
0 quit
...
11 <hang>
Which indicates that webdriver.Remote is refusing to properly initiate the driver. This also occurs when the driver instance is constructed directly with webdriver.Chrome (instead of running the ChromeDriver as a service).
After sending SIGINT to the hanging program, I get a stacktrace (pastebin) indicating a blocking socket read somewhere in the constructor.
ChromeDriver's log (dropcanvas) doesn't seem to indicate anything amiss, and I'm quite puzzled as to what is happening here.
Similar questions have been asked previously, the most relevant being Selenium Chromedriver Hangs?; however, I cannot reproduce the accepted solution (starting Xvfb anew for each instantiation of webdriver...). Here, the equivalent would be calling Xvfb.start immediately preceding d = webdriver.Remote... and calling Xvfb.stop at the end of the loop; I have tried this to no success.
Any help would be greatly appreciated.
Edit: As indicated by the stacktrace, webdriver.Remote was hanging on some socket read function; I traced the request to be
POST 'http://127.0.0.1:<chromedriver_port>/session'
with body
'{"desiredCapabilities": {"platform": "ANY", "browserName": "chrome", "version": "", "javascriptEnabled": true}}'
So it seems like ChromeDriver isn't responding for some reason. Will continue debugging.

Why Wait.until() doesn't work in Selenium WebDriver?

I have been using Selenium WebDriver. I want to wait until the element is present on the webpage, for which i am using:
WebDriverWait wait = new WebDriverWait(driver, Long.parseLong(timeout));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator)));
but my test get stucks in the second line if the element I am looking for, is not present and even beyond the timeout. Pls Help. Thanks.
Maybe:
- the element is present, so no exception is thrown
- then gets stuck because you are not doing anything else afterwards
Try printing smt after the until call. My guess is it will get printed.
Otherwise maybe it's the timeout:
It must be in seconds, not milli seconds.
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html#WebDriverWait(org.openqa.selenium.WebDriver, long)
I got it worked. I changed the timeout from 60000 to 60 since it takes the second argument as seconds and not millisecs.

Selenium SelectWindow Command not working

Selenium Select Window command fails and shows "Could not find window with title....". but if i Execute the Select Window command alone it passes the case and verifying the elements.
Code i used:
public void testDefaultlogo() throws Exception {
selenium.open("http://Sitename/samp.aspx");
selenium.type("ctl00_mainContentPlaceHolder_txt_LoginName", "uname");
selenium.type("ctl00_mainContentPlaceHolder_txt_Password", "pwd#12");
selenium.click("ctl00_mainContentPlaceHolder_btn_login");
selenium.waitForPageToLoad("60000");
selenium.click("ctl00_defaultLogo");
selenium.selectWindow("Sample~Window-ID");
verifyEquals("http://Sitename/index.html", selenium.getLocation());
selenium.close();
selenium.selectWindow ("null");
verifyTrue(selenium.isElementPresent("ctl00_defaultLogo"));
I mean by clicking one by one of the follwing commands in Selenium IDE it shows green but if i run the case it failed and shows as i mentioned above
What I can get from your code is that, clicking the "ctl00_defaultLogo" will popup another window. The possible issue could be that after write the command selenium.click("ctl00_defaultLogo") you need to wait for the popup to load.
The possible resolution, insert the command
selenium.WaitForPopUp("Sample~Window-ID", "5000");
before the
selenium.selectWindow("Sample~Window-ID");
This will cause selenium to wait for 5 secs before selecting the popup window.
Hope this helps!!!
some times it may not work for that u better use.
open_window("URL","WindowID or title or name");
selenium.selectWindow("WindowID or title or name");

Selenium test in Internet Explorer always times out?

I'm trying to run a basic test in Internet Explorer via Selenium-RC/PHPUnit, and it always returns with
# phpunit c:\googletest.php
PHPUnit 3.4.15 by Sebastian Bergmann.
E
Time: 35 seconds, Memory: 4.75Mb
There was 1 error:
1) Example::testMyTestCase
PHPUnit_Framework_Exception: Response from Selenium RC server for testComplete()
.
Timed out after 30000ms.
C:\googletest.php:17
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Paul#PAUL-TS-LAPTOP C:\xampp
#
The last command in command history is waitForPageToLoad(30000). The same test runs fine and completes in firefox. How can I get this test to run and complete in internet explorer?
Thanks
There's an open bug in selenium that causes waitForPageToLoad to sometimes timeout on IE.
http://jira.openqa.org/browse/SRC-552
It's marked as occurring on IE6, but I'm experiencing the same error in at least IE9.
A workaround is to wait for e.g. a specific DOM-element on the page that is loading instead of using waitForPageToLoad. For example: waitForVisible('css=#header')
Try going into Internet Options and turn off Protected mode under the security tab. You may also want to decrease the security level for the Internet zone.
I've turned off protected mode and looks like it helped.
If it is acceptable to customize the client driver, here is the Python implementation for your refernece:
def open(self):
timeout = self.get_eval('this.defaultTimeout')
self.set_timeout(0)
self.do_command("open", [url,ignoreResponseCode])
self.set_timeout(timeout)
self.wait_for_page_to_load(timeout)
def wait_for_page_to_load(self,timeout):
# self.do_command("waitForPageToLoad", [timeout,])
import time
end = time.time() + int(float(timeout) / 1000)
while time.time() < end:
if self.get_eval('window.document.readyState') == 'complete': return
time.sleep(2)
raise Exception('Time out after %sms' % timeout)
I just use DOM attribute document.readyState to determine if the page is fully loaded.
IE 9+ intermittently throws a timeout error even the page is fully loaded, for more details.