首页 > 解决方案 > selenium.common.exceptions.WebDriverException:unknown error:cannot connect to chrome at 127.0.0.1:9222 from unknownerror:unable to discover open pages

问题描述

我设法在 python 中使用以下方法将 selenium 驱动程序连接到已经打开的 chrome 会话

def iniciar_google_previa():
   os.system('google-chrome --no-sandbox --remote-debugging-port=9222 --user-data-dir="/home/natanael/.config/google-chrome/Default" &')
   time.sleep(2)
   options1 = Options()
   options1.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
   chrome_driver = "/usr/local/bin/chromedriver"
   driver = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options1)
   
   return driver

它工作得非常好,然后我可以打开任何网站driver.get("site_url")开始抓取。

我想对 docker 容器进行同样的尝试。安装了 dockerfile 的所有要求,构建它,然后尝试运行它,但我收到以下错误

  File "final1.py", line 104, in <module>
   iniciar_ciclo()
 File "final1.py", line 21, in iniciar_ciclo
   driver = iniciar_google_previa()
 File "final1.py", line 67, in iniciar_google_previa
   driver = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options1)
 File "/opt/app-root/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
   desired_capabilities=desired_capabilities)
 File "/opt/app-root/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
   self.start_session(capabilities, browser_profile)
 File "/opt/app-root/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
   response = self.execute(Command.NEW_SESSION, parameters)
 File "/opt/app-root/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
   self.error_handler.check_response(response)
 File "/opt/app-root/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
   raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:9222
from unknown error: unable to discover open pages

我以为是因为它试图运行 GUI,所以我添加了 --headless

google-chrome --no-sandbox --headless --remote-debugging-port=9222 --user-data-dir="/home/natanael/.config/google-chrome/Default" 但得到了同样的错误。

已经尝试安装 xvfb

接着

xvfb-run google-chrome --no-sandbox --remote-debugging-port=9222 --user-data-dir="/home/natanael/.config/google-chrome/Default"

这给出了输出

DevTools listening on ws://127.0.0.1:9222/devtools/browser/52bbc92b-e096-4897-8661-233ee573edaf

显然它执行了 chrome 会话,但仍然无法连接到它,我不知道还能尝试什么

标签: pythondockerseleniumselenium-webdriver

解决方案


推荐阅读