如何关闭Selenium打开的所有窗口?

4 投票
3 回答
7720 浏览
提问于 2025-04-16 02:21

我现在正在使用Selenium RC来进行一些测试,驱动程序是用Python写的。

不过,我遇到了一个问题:每次Selenium RC运行并打开一个网址时,它会打开两个窗口,一个是用来登录的,另一个是用来显示HTML内容的。但是我在脚本中无法关闭这两个窗口。

这是我的脚本:

#!/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()

这个脚本很简单明了。我真正想要的是关闭Selenium打开的所有窗口。我试过使用close()和stop(),但都没有效果。

3 个回答

0

我建议用Python写一个系统命令来关闭Firefox窗口。

Bussiere

1

我解决了这个问题。
问题出在我安装了firefox-bin,而不是正常的firefox。
现在我把firefox-bin卸载了,安装了真正的firefox,现在一切正常了。
stop()这个命令会关闭所有selenium打开的窗口。

感谢你的提醒 AutomatedTester

7

我遇到过类似的情况,当我在抓取一个网页时,我的程序打开了很多窗口。这是一个示例代码:

#!/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()   

我一直被“driver.close()”这个问题困扰了一个星期,因为我以为它会关闭所有窗口。其实“driver.quit()”是用来结束所有进程并关闭所有窗口的。

撰写回答