【问题标题】:Chrome browser closes automatically when run chromedriver inside a method/function在方法/函数中运行 chromedriver 时,Chrome 浏览器会自动关闭
【发布时间】:2019-06-13 08:44:03
【问题描述】:

我试图在 Pycharm IDE 中的 chrome 浏览器中运行一些 selenium 测试。我在函数中编写了 chrome 驱动程序,当我尝试运行代码时,它会打开浏览器并在一秒钟内自动关闭。但是当我写功能之外的chrome驱动程序它打开浏览器并且没有关闭。如果我在方法/函数中编写 chromedriver 代码,如何使浏览器保持打开状态?

代码:

from selenium import webdriver
import os

class Chrome:
    def Run(self):
        driverLocation="F:\\Workspace py\chromedriver\chromedriver.exe"
        os.environ["webdriver.chrome.driver"] = driverLocation
        driver = webdriver.Chrome(driverLocation)
        driver.get("https://www.google.com")


Test=Chrome()
Test.Run()

【问题讨论】:

  • 由于driverRun函数中的一个局部变量,我敢打赌Python解释器会自动关闭浏览器窗口,因为Run函数退出了。

标签: python-3.x selenium


【解决方案1】:

这对我有用:

from selenium import webdriver
import os

class Chrome:
    def Run(self):
        self.driverLocation="F:\\Workspace py\chromedriver\chromedriver.exe"
        os.environ["webdriver.chrome.driver"] = self.driverLocation
        self.driver = webdriver.Chrome(driverLocation)
        self.driver.get("https://www.google.com")


Test=Chrome()
Test.Run()

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2021-03-04
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 2016-03-03
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多