在Docker容器中使用Selenium遇连接拒绝错误求助
解决Docker容器中Selenium连接拒绝错误
核心问题分析
- Remote WebDriver连接地址错误:你的
test.py里把command_executor写成了http://webapp:4444/wd/hub,但webapp是自身Python服务容器,Selenium Grid服务运行在名为selenium的容器中,连接地址需指向该服务名。 - 服务就绪等待不可靠:
time.sleep(5)无法保证Selenium Grid完全启动,首次启动时Chrome初始化可能需要更长时间。 - Alpine镜像依赖缺失:Python Alpine镜像缺少Chrome运行所需的系统依赖,可能导致连接成功后仍无法启动浏览器。
分步解决方案
1. 修正Remote连接地址
修改test.py中的command_executor配置:
driver = webdriver.Remote( command_executor='http://selenium:4444/wd/hub', # 替换为selenium服务名 options=chrome_options )
2. 替换为可靠的服务就绪等待
移除time.sleep(5),改用循环检查Selenium Grid健康接口,确保服务就绪后再执行脚本:
from selenium import webdriver import time import requests # 等待Selenium Grid服务就绪 def wait_for_selenium(): while True: try: response = requests.get('http://selenium:4444/wd/hub/status') if response.status_code == 200 and response.json()['value']['ready']: break except requests.exceptions.ConnectionError: pass time.sleep(1) wait_for_selenium() # 后续初始化Remote WebDriver代码保持不变
同时在Dockerfile中添加requests依赖:
RUN pip install selenium requests
3. 更换Python基础镜像(推荐)
Alpine镜像缺少Chrome运行依赖,改用Debian-based的python:3.10-slim镜像,避免依赖缺失问题:
修改Dockerfile:
# 使用Debian-based的Python镜像 FROM python:3.10-slim # 安装Chrome运行所需系统依赖 RUN apt-get update && apt-get install -y --no-install-recommends \ libnss3 \ libfontconfig1 \ && rm -rf /var/lib/apt/lists/* # 安装Selenium和requests RUN pip install selenium requests RUN mkdir /app WORKDIR /app COPY test.py /app/
4. 优化docker-compose健康检查(可选)
添加健康检查规则,让docker-compose自动等待Selenium服务就绪后再启动webapp:
version: '3' services: selenium: image: selenium/standalone-chrome ports: - "4444:4444" restart: always shm_size: 2g healthcheck: test: ["CMD", "curl", "-f", "http://localhost:4444/wd/hub/status"] interval: 5s timeout: 10s retries: 5 webapp: build: context: . volumes: - .:/app command: sh -c "python3 test.py" depends_on: selenium: condition: service_healthy # 等待selenium健康检查通过
验证修改
执行docker-compose up --build,webapp容器会等待Selenium Grid完全就绪后再运行脚本,连接地址正确的情况下,将成功生成search_results.png截图。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

