首页 > 解决方案 > 如何检查硒铬窗口是否关闭python

问题描述

我正在做一个桌面助手,它可以打开并登录我的 Instagram。但是当我关闭 Instagram chrome 窗口时,循环并没有结束。那么如何检查窗口是否关闭并结束循环呢?

class Instagram:
    def __init__(self):
        self.driver=webdriver.Chrome('chromedriver.exe')
        sleep(2)
        self.driver.get('https://www.instagram.com/accounts/login/')
        self.driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input').send_keys("username")
        self.driver.find_element_by_xpath("//input[@name=\"password\"]").send_keys("pass")
        self.driver.find_element_by_xpath('//button[@type="submit"]').click()

        sleep(4)
        self.driver.find_element_by_xpath("/html/body/div[1]/section/main/div/div/div/div/button").click()
        sleep(4)
        self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div/div[3]/button[2]").click()
        sleep(4)
        self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div/div[3]/button[2]").click()
        
        sleep(5)
        while x == 1:
            sleep(10)
x = 1

if "open instagram" in query:
    Instagram()

标签: pythonseleniumgoogle-chromewindowinstagram

解决方案


WebDriverException如果用户关闭窗口,您可以通过在尝试与驱动程序交互时捕获 a来解决此问题。例如,您可以添加

try:
    self.driver.get('example.com')
except WebDriverException: 
    print("user has closed the window")
    # do something with that 
    break

到最后的循环__init__

此外,x代码中 never 的值会发生变化,因此它是一个无限循环。除非您在其他地方更改值。


推荐阅读