You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker中Selenium Remote连接挂起及连接拒绝问题求助

解决Docker中Selenium Remote连接问题

核心问题分析

  1. Remote初始化参数缺失:创建Remote驱动时未传入配置好的ChromeOptions,导致Selenium Grid无法正确匹配浏览器节点,引发挂起。
  2. 连接地址错误:
    • 若代码在宿主机运行:直接使用容器IP(172.25.0.2)存在网络隔离问题,且未将Selenium端口映射到宿主机;
    • 若代码在web容器内运行:http://chrome:4444需补充Selenium Grid的标准路径/wd/hub(部分Selenium 4版本可省略,兼容旧版本建议加上)。

分步解决方案

1. 修正Python连接代码

必须将配置好的ChromeOptions传入Remote驱动,同时指定对应环境的Grid地址:

from selenium.webdriver import ChromeOptions, Remote

options = ChromeOptions()
options.add_argument('--headless=new')  # Selenium 4+推荐使用该参数替代旧版--headless
options.add_argument('--no-sandbox')    # 容器环境下添加,避免权限限制
options.add_argument('--disable-dev-shm-usage')  # 解决容器shm空间不足问题

# 根据运行环境选择地址:
# 场景1:代码在web容器内部运行
driver = Remote(command_executor='http://chrome:4444/wd/hub', options=options)
# 场景2:代码在宿主机运行(需先给chrome服务映射端口)
# driver = Remote(command_executor='http://localhost:4444/wd/hub', options=options)

2. 调整Docker Compose配置(宿主机运行代码场景)

如果需要从宿主机直接连接Selenium服务,给chrome服务添加端口映射:

chrome:
  image: selenium/standalone-chrome
  hostname: chrome
  privileged: true
  shm_size: 2g
  ports:
    - "4444:4444"  # 映射Grid端口到宿主机
    - "7900:7900"  # 可选,映射VNC端口用于可视化查看浏览器

3. 验证网络连通性

  • 若在web容器内运行代码,先进入容器测试:
    docker exec -it my_app-web-1 ping chrome
    # 测试端口连通性
    docker exec -it my_app-web-1 curl http://chrome:4444/wd/hub/status
    
    返回JSON格式的节点状态信息即表示网络连通正常。
  • 若在宿主机测试:
    curl http://localhost:4444/wd/hub/status
    

4. 确保版本兼容性

保证Python的selenium包版本与容器内Selenium Grid版本(日志显示为4.7.2)一致,避免版本不兼容问题:

pip install selenium==4.7.2

内容的提问来源于stack exchange,提问作者watch-this

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:00:59