以下代码部分假设在异常发生时终止(停止)程序,并带有
driver.quit()
。但是,程序继续运行。我在这里错过了什么?
try:
driver.refresh()
wait.until(ec.visibility_of_element_located(
(By.XPATH, "//p[text()='Move']")))
print("Waiting for Move")
time.sleep (1)
except:
print("All Move Completed")
driver.quit()
您不应该在
driver.quit()
之后连续打电话给 driver.close()
。
完全删除
driver.close()
。只需保留 driver.quit()
即可完成工作。
您的有效代码块将是:
while True:
try:
driver.refresh()
wait.until(ec.visibility_of_element_located((By.XPATH, "//p[text()='Move']")))
print("Waiting for Move")
continue
except TimeoutException:
break
print("All Move Completed")
driver.quit()
Selenium 中的 driver.quit() 方法旨在关闭浏览器窗口并释放相关资源,但它并不一定会终止整个 Python 进程。如果 driver.quit() 之后还有后续代码行,它们将继续执行。
为了确保您的代码在退出驱动程序后停止执行,您可以显式添加 sys.exit() 调用或引发异常。这是一个例子:
Python
import time
from selenium import webdriver
import sys
# Initialize the driver (your setup code here)
try:
driver.get("https://music.apple.com/us/browse")
# Your other actions here
except Exception as e:
print(f"Error: {e}")
finally:
driver.quit()
sys.exit() # This will terminate the entire Python process
通过添加 sys.exit(),您可以确保脚本在退出驱动程序后立即停止。根据您的特定用例的需要调整错误处理和代码的其他部分。 😊