Python Selenium:如果空闲,请退出浏览器

2024-05-06 07:54:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过以下方式列出无头Chrome网络驱动程序:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--log-level=3')
browsers = {}

def add_browser(browser_id):
     browsers[browser_id] = webdriver.Chrome(executable_path=chromedriver, options=options)
     browsers[browser_id].get(URL)

但是,我想关闭那些已经处于活动状态和空闲状态太长时间的浏览器。我该如何实施

如果有帮助的话-这是用于烧瓶应用程序的


Tags: from网络browseraddidselenium方式驱动程序
1条回答
网友
1楼 · 发布于 2024-05-06 07:54:08
from datetime import datetime

def add_browser(browser_id):
     browsers[browser_id] = {
          browser: webdriver.Chrome(executable_path=chromedriver, options=options),
          last_active: datetime.now()
     }
     browsers[browser_id][browser].get(URL)
     // do some stuff... scrape links? navigate through pages? input text?

然后,在//do some stuff部分编写脚本时,现在可以执行以下两项操作之一:

// "check in" to confirm the session is still active
browsers[browser_id][last_active] = datetime.now()
// during a loop that you are worried about getting stuck in due to the browser being idle
idle_time = datetime.now() - browsers[browser_id][last_active]
if idle_time.seconds > maximum_idle_time:
     browsers[browser_id][browser].quit()

相关问题 更多 >