我正在尝试关闭我的应用程序在用户中断程序时打开的Firefox实例。但是selenium不会关闭这扇窗。以下是显示问题的示例代码:
import time
from selenium import webdriver
driver = webdriver.Firefox()
try:
while True:
driver.get("https://google.com")
time.sleep(5)
except KeyboardInterrupt:
print("Quitting")
driver.quit()
print("Done")当我点击Ctrl+C时,我看到控制台上打印了“退出”,几分钟后,我看到控制台上打印了“完成”,程序结束。但firefox窗口仍处于打开状态。如何解决这个问题?
编辑:
import time
from selenium import webdriver
driver = webdriver.Firefox()
try:
for i in range(5):
print("Looping")
driver.get("https://google.com")
time.sleep(5)
except KeyboardInterrupt:
print("Quitting")
driver.quit()
print("Done")
driver.quit()
print("After loop and stuff")这也行不通。如果等待循环结束,浏览器将成功关闭。但是如果你在循环中间点击Ctrl+C,浏览器仍然是打开的。
发布于 2020-02-06 19:57:23
我做了一个关于这个问题的研究,并查看了github上Stackoverflow和Selenium论坛上所有可用的资源。
同样的问题也引发了here,后来由于没有适当的解决方案而关闭。您可以在此处查看详细信息。此问题特定于Windows和firefox。它在MAC OS上运行良好。我知道它发生的主要原因是因为Geckodriver崩溃了,你可以在这里查看geckodriver-logs
他们已经尝试了最新的Python绑定和最新的Geckodriver。没有干净的解决方案,取而代之的是解决方法杀死由火狐驱动程序生成的firefox.exe进程。
请看一下。
tasklist = check_output(["tasklist", "/fi", "imagename eq firefox.exe"], shell=True).decode()
currentFFIDs = re.findall(r"firefox.exe\s+(\d+)", tasklist)
driver = webdriver.Firefox(options=opts, executable_path='./bin/geckodriver.exe')
tasklist = check_output(["tasklist", "/fi", "imagename eq firefox.exe"], shell=True).decode()
firefoxIds = set(re.findall(r"firefox.exe\s+(\d+)", tasklist)).difference(currentFFIDs)
# do your stuff
try:
driver.close()
driver.quit()
# Could't close the driver via normal means-- Force Close #
except:
taskkill = 'taskkill /f '+''.join(["/pid "+f+" " for f in firefoxIds]).strip()
check_output(taskkill.split(), shell=True)
print("\nHAD TO FORCE-CLOSE FIREFOX", flush=True)发布于 2020-02-04 20:48:27
您可以尝试在代码中使用with语句,详细信息可以在here中找到
import time
from selenium import webdriver
driver = webdriver.Firefox()
with driver:
while True:
driver.get("https://google.com")
time.sleep(5)如果您想捕获KeyboardInterrupt或/和SystemExit,您可以找到有用的信息here。
我在终端和Firefox中测试了我的代码和下面的代码,完全符合预期:
import time
from selenium import webdriver
driver = webdriver.Firefox()
try:
for i in range(5):
print("Looping")
driver.get("https://google.com")
time.sleep(5)
except KeyboardInterrupt:
print("quitting: KeyboardInterrupt")
finally:
driver.quit()
print("Done")发布于 2020-02-02 19:52:46
没有为while循环提供终止条件...您的while循环正在无休止地运行。键盘中断块永远不会执行,因为控件不会离开while循环。
https://stackoverflow.com/questions/60025735
复制相似问题