我正在制作一个桌面助手,它可以打开并登录我的 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()
最佳答案
如果用户关闭了窗口,您可以通过在尝试与驱动程序交互时捕获 WebDriverException
来确定这一点。
例如,您可以添加
try:
self.driver.get('example.com')
except WebDriverException:
print("user has closed the window")
# do something with that
break
到__init__
末尾的循环
此外,x
的值在代码中永远不会改变,因此它是一个无限循环。除非您在其他地方更改该值。
关于python - 如何检查selenium chrome窗口是否关闭python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62610165/