强制Docker容器中的SeleniumHQ关闭所有浏览器会话

时间:2019-02-08 08:58:36

标签: python-3.x selenium docker

我在docker容器中运行selenium hub来测试网站。 我的Dockerfile的相关部分是:

#https://github.com/SeleniumHQ/docker-selenium
version: '3'
services:
selenium-hub:
    image: selenium/hub:3.141.59-dubnium
    environment:
    - GRID_MAX_SESSION=15
    - GRID_TIMEOUT=180000
    - GRID_BROWSER_TIMEOUT=180000      
    networks: 
    - selenium-hub
chrome:
    image: selenium/node-chrome:3.141.59-dubnium
    shm_size: 512MB
    volumes:
    - /dev/shm:/dev/shm
    depends_on:
    - selenium-hub
    environment:
    - NODE_MAX_INSTANCES=5
    - NODE_MAX_SESSION=6
    - HUB_HOST=selenium-hub
    - HUB_PORT=4444
    - DBUS_SESSION_BUS_ADDRESS=/dev/null
    networks: 
    - selenium-hub

我编写了python 3.x脚本以连接到硒。通常的例程如下。但是有时driver变量会由于外部错误而丢失。在这种情况下,Selenium网格保存了我已经失去控制的待处理浏览器会话。是否可以强制Selenium hub一次关闭所有浏览器会话?如何在python中做到这一点?

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

cap = DesiredCapabilities.CHROME
driver = webdriver.Remote(command_executor='http://selenium-hub:4444/wd/hub',desired_capabilities=cap) 
##
# commands to browser
##
driver.quit()

1 个答案:

答案 0 :(得分:0)

您可以使用try / finally结构代码:

driver = webdriver.Remote(command_executor='http://selenium-hub:4444/wd/hub', desired_capabilities=cap)
try:
    ##
    # commands to browser
    ##
finally:
    driver.quit()

或将您的驱动程序创建为上下文管理器:

with webdriver.Remote(command_executor='http://selenium-hub:4444/wd/hub', desired_capabilities=cap) as driver:
    ##
    # commands to browser
    ##

...这两个都将始终在您的驱动程序实例上调用quit()

注意:即使它们将无条件调用quit(),也不一定意味着浏览器实际上会关闭。