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

Selenium Chrome无头浏览器偶发挂起问题求助

Selenium无头Chrome获取OAuth2授权码偶发冻结问题

我用Python写了一段代码,功能是启动--headless=new模式的Chrome,加载指定的Chrome配置文件,从跳转URL中提取OAuth2授权码。使用的Selenium版本是4.8.0。

代码大部分时候运行正常,但每4次启动就会出现一次完全冻结的情况——卡在着陆页,无法提取授权码,仅输出USB、蓝牙相关的错误日志,没有其他有效反馈。

我试过用Selenium Stealth,没用;也试过启动前用子进程杀掉所有chrome.exe进程,问题依旧。

完整函数代码

async def allegroCODE(status):
        status.update(status="[bold green]Zdobywanie kodu...",spinner="bouncingBall", spinner_style="yellow")
        authorization_redirect_url = CODE_URL + '?response_type=code&client_id=' + CLIENT_ID + \
                                    '&redirect_uri=' + REDIRECT_URL
        try:
            FNULL = open(os.devnull, 'w')
            subprocess.call("taskkill /F /IM chrome.exe",stdout=FNULL,stderr=subprocess.STDOUT)
        except:
            pass
        await asyncio.sleep(5)
        options = webdriver.ChromeOptions()
        # options.add_argument("--log-level=3")
        options.add_argument("--headless=new")
        options.add_argument("user-data-dir=C:\\Users\\crepe\\AppData\\Local\\Google\\Chrome\\User Data\\")
        options.add_argument("profile-directory=Profile 1")
        options.add_experimental_option('excludeSwitches', ['enable-logging'])
        ser = Service(r"C:\chromedriver.exe")
        driver = webdriver.Chrome(service=ser, options=options, service_log_path=os.path.devnull)
        driver.set_page_load_timeout(15)
        # stealth(driver,
        #         languages=["en-US", "en"],
        #         vendor="Google Inc.",
        #         platform="Win32",
        #         webgl_vendor="Intel Inc.",
        #         renderer="Intel Iris OpenGL Engine",
        #         fix_hairline=True,
        #         )

        driver.get(authorization_redirect_url)
        code = driver.current_url
        driver.quit()
        code = code.split('=')
        code_ex = code[1]
        console.log(f"[bold green]✅ Udało się zdobyć kod: {code_ex}")
        authorization_code = code_ex
        return authorization_code

补充错误日志(已翻译)

DevTools 监听 ws://127.0.0.1:1059/devtools/browser/0497f13c-2bc0-439d-8a8f-2d5c2a597cb7
[17848:12192:0214/231451.183:ERROR:device_event_log_impl.cc(215)] [23:14:51.183] USB: usb_device_handle_win.cc:1046 无法从节点连接读取描述符:连接到计算机的设备无法正常工作。(0x1F)

[17848:12192:0214/231451.183:ERROR:device_event_log_impl.cc(215)] [23:14:51.183] Bluetooth: bluetooth_adapter_winrt.cc:1074 获取默认适配器失败。
[17848:12192:0214/231451.185:ERROR:device_event_log_impl.cc(215)] [23:14:51.184] USB: usb_device_handle_win.cc:1046 无法从节点连接读取描述符:连接到计算机的设备无法正常工作。(0x1F)

之前在论坛搜过类似问题,但没找到解决办法,特来求助。

内容的提问来源于stack exchange,提问作者Alotofproblemshere

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:45:20