selenium SessionNotCreatedException问题解决办法

发布于:2025-08-12 ⋅ 阅读:(14) ⋅ 点赞:(0)

        在上周有一台服务器重启之后,Chrome浏览器也自动升了级,原本能够正常使用的自动化办公程序突然没法用了,出现了下面的报错提示。

codes/addCancelBdld.py:980: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path='./chromedriver.exe', desired_capabilities=desired_capabilities, chrome_options=chrome_options)
[13908:16748:0731/133626.719:ERROR:net\base\network_change_notifier_win.cc:189] WSALookupServiceBegin failed with: 8

DevTools remote debugging requires a non-default data directory. Specify this using --user-data-dir.
[6080:23036:0731/133626.876:ERROR:net\base\network_change_notifier_win.cc:189] WSALookupServiceBegin failed with: 8
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1753940192.016375    5356 voice_transcription.cc:58] Registering VoiceTranscriptionCapability
[13908:16748:0731/133643.763:ERROR:components\device_event_log\device_event_log_impl.cc:198] [13:36:43.764] Bluetooth: bluetooth_adapter_winrt.cc:1054 Getting Default Adapter failed.
......
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: DevToolsActivePort file doesn't exist

        经过多次询问DeepSeek也未能找到原因,但好在我已经找到了解决方法。

        我在代码中指定了--user-data-dir为User Data目录。这是导致代码运行时出现上面报错的罪魁祸首。

chrome_options.add_argument(f"--user-data-dir={os.path.join(os.environ['USERPROFILE'], fr'AppData/Local/Google/Chrome/User Data')}")

        我将User Data目录更名为Selenium Data,并将代码中的--user-data-dir指定为更名后的Selenium Data目录,代码就能正常使用了。

        最后,右键桌面上的Chrome快捷方式,点属性,在目标那一栏的内容后面加上--user-data-dir,也指定为更名后的Selenium Data目录。

--user-data-dir="%LOCALAPPDATA%\Google\Chrome\Selenium Data"

        这样桌面上的Chrome快捷方式也能正常使用了。