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

Python QA自动化入门遇Selenium报错:urllib3.exceptions.MaxRetryError求助

问题原因分析

你的代码存在对象混用的核心问题:同时手动初始化了driver = webdriver.Chrome(),又依赖pytest-selenium提供的selenium fixture,两者会创建独立的浏览器会话,导致后续操作时连接冲突,触发urllib3.exceptions.MaxRetryError。

修复方案

完全基于pytest-selenium的fixture编写测试,无需手动创建和管理driver对象,pytest-selenium会自动处理浏览器的启动与关闭。修改后的代码如下:

import time
from selenium.webdriver.common.by import By

def test_search_example(selenium):
    """ 在谷歌搜索指定内容并截图 """
    # 打开谷歌搜索页
    selenium.get('https://google.com')

    # 等待页面加载(建议后续用显式等待替代固定sleep)
    time.sleep(5)  

    # 定位搜索输入框
    search_input = selenium.find_element(By.NAME, "q")

    # 输入搜索文本
    search_input.clear()
    search_input.send_keys('first test')

    time.sleep(5) 

    # 点击搜索按钮
    search_button = selenium.find_element(By.NAME, "btnK")
    search_button.click()

    time.sleep(10)  

    # 保存页面截图
    selenium.save_screenshot('result.png')
额外优化建议
  • 替换固定等待为显式等待:避免固定sleep导致的不稳定,示例代码如下:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 等待搜索框加载完成,最多等待10秒
    search_input = WebDriverWait(selenium, 10).until(
        EC.presence_of_element_located((By.NAME, "q"))
    )
    
  • 匹配ChromeDriver版本:确保本地ChromeDriver版本与Chrome浏览器版本完全一致,版本不兼容也会引发连接类问题。
  • 清理残留进程:打开任务管理器,结束所有chromedriver.exe和Chrome相关的残留进程后,再重新运行测试。

内容的提问来源于stack exchange,提问作者piranesi-27

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:45:36