【发布时间】:2019-11-25 16:57:08
【问题描述】:
对此新手表示歉意。
尝试使用 Python、Selenium 和 unittest 模块运行脚本。具有典型的 setUp()、test_1、test_2、tearDown() 方法结构。由于我添加了多个测试,因此出现以下错误: selenium.common.exceptions.InvalidSessionIdException:消息:尝试在未建立连接的情况下运行命令
我该如何解决这个问题?
我已经调查过人们在这个问题上遇到的类似问题,但在几乎所有情况下,这个问题都与我遇到的任何事情无关(例如 cronjobs)
我的程序是这样的……
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
#my setup code here...
cls.driver = webdriver.Firefox(executable_path='my_gecko_driver')
cls.driver.get('www.my_url.com')
cls.driver...... # various other tasks
def test_1(self):
# my test code here....
foo = self.driver.find_element_by_xpath('/button_elem/')
foo.click()
# etc etc....
def test_2(self):
# my test code here....
bar = self.driver.find_element_by_xpath('/button_elem/')
bar.click()
# etc etc....
@classmethod
def tearDown(cls):
print('Entered tearDown function.')
# close the browser window
cls.driver.close()
if __name__ == '__main__':
unittest.main()
在我添加第二个测试之前,测试运行成功。
现在我收到错误消息: selenium.common.exceptions.InvalidSessionIdException:消息:尝试在未建立连接的情况下运行命令
我怀疑这与 tearDown 方法可能无法正常工作有关?但是我认为这个方法是在每个 test_x 结束时调用的。
我还注意到 Pycharm 在“cls.driver.close()”行中突出显示了“驱动程序”,我也不太确定。它说未解析的属性引用'但是这不是在 setUp() 方法中创建的吗?
【问题讨论】:
-
driver.close 关闭浏览器窗口...(如果这是最后一个打开的窗口,某些驱动程序也会退出驱动程序)之后您将无法执行任何操作,因为没有用于检查元素的窗口或文档。
-
感谢@pcalkins 的回复,那我还有什么选择呢?我试过 driver.close() 和 driver.quit() 都导致我出现同样的错误。
-
要么不要关闭它(如果你确实想关闭驱动程序,你可能应该使用 .quit() ......这也会关闭浏览器)或者创建一个新的驱动程序实例并打开一个查找元素之前的 URL。
标签: python-3.x selenium geckodriver