python - 如何检查硒铬窗口是否关闭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()
解决方案
WebDriverException
如果用户关闭窗口,您可以通过在尝试与驱动程序交互时捕获 a来解决此问题。例如,您可以添加
try:
self.driver.get('example.com')
except WebDriverException:
print("user has closed the window")
# do something with that
break
到最后的循环__init__
此外,x
代码中 never 的值会发生变化,因此它是一个无限循环。除非您在其他地方更改值。
推荐阅读
- winapi - WinApi:使用 VirtualAlloc 跨两个进程共享内存
- python - 合并两个大熊猫数据框
- bash - 如何使用 sed 更改文件中多行的字符串
- python - PyGObject Gtk.TreeView 中的微调器不旋转
- asp.net - 无法将“配置转换”添加到我的 web.config 文件
- django - django debug false 的意外行为
- firebase - firebase 注销不适用于 FB 托管
- c# - EWS: BindToRecurringMaster 很慢,只需要经常性的master Id
- jquery - Jquery在提交表单时显示加载div(文件上传)
- python - 元类传递类名作为参数