Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close all windows that Selenium opens?

I am using Selenium RC to do some test now. And the driver I use is python.

But now, I faced a problem, that is: every time Selenium RC runs, and open a url, it opens 2 windows, one is for logging and the other one is for showing HTML content. But I can't close them all in script.

Here is my script:

#!/usr/bin/env python
#-*-coding:utf-8-*-
from selenium import selenium

def main():
    sel = selenium('localhost', 4444, '*firefox', 'http://www.sina.com.cn/')
    sel.start()
    try:
        sel.open('http://www.sina.com.cn/')
    except Exception, e:
        print e
    else:
        print sel.get_title()
    sel.close()
    sel.stop()

if __name__ == '__main__':
    main()

It is very easy to understand. What I really want is to close all windows that selenium opens. I've tried close() and stop(), but they all don't work.

like image 655
davidx Avatar asked Feb 27 '23 12:02

davidx


2 Answers

I had a similar case where my program opened many windows when scraping a webpage. here is a sample code:

#!/usr/bin/python
import webbrowser
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
print "Browser fired-up!"
driver.get("https://www.something.com/")
driver.implicitly_wait(5)

while True:

    try:
        playlink = driver.find_element_by_xpath("/html/body/div[2]/div[1]/div/a")
        playlink.click()
        time.sleep(3)
    except NoSuchElementException: 
        print "playlink Element not found "
    else:
        backbutton = driver.find_element_by_id("back-to-bing-text")
        backbutton.click()

    try:
        quizlink = driver.find_element_by_xpath("/html/body/div[2]/div[1]/div[1]/ul/li[1]/a/span/span[1]")
        quizlink.click()
    except NoSuchElementException: 
        print "quiz1 Element not found "
    else:
        print "quiz1 clicked"

    driver.quit()   

The "driver.close()" bugged me for a week as I believed it would close all the windows. "driver.quit()" is to terminate all the process and close all the windows.

like image 83
zwon Avatar answered Mar 01 '23 01:03

zwon


I've fix this problem. It happens because I installed firefox-bin not firefox. Now I've removed firefox-bin and have installed firefox, it works now. stop() will close all windows that selenium opened.

Thank you for your reminds AutomatedTester

like image 30
davidx Avatar answered Mar 01 '23 01:03

davidx