首页 > 解决方案 > 在 Google colaboratory 中 Selenium 无法工作(没有新的 chrome 弹出)

问题描述

我在 Google Colaboratory 上的 Selenium 遇到了麻烦。

我已尝试自动登录我所在国家/地区的门户网站。我了解到,当我运行代码时,应该打开新的 chrome 窗口。

但是我运行了下面的代码,即使没有错误消息也没有发生任何事情。

!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',chrome_options=chrome_options)

wd.get("https://nid.naver.com/nidlogin.login")

sleep(0.5)
wd.find_element_by_name('id').send_keys('ID')
sleep(0.5)
wd.find_element_by_name('pw').send_keys('password')

运行完成但我没有任何结果...如何获得新窗口?

标签: pythonseleniumgoogle-colaboratory

解决方案


Google Colaboratory在服务器上运行代码,Chrome 也在服务器上运行 - 因此 Chrome 只能在连接到该服务器的显示器上显示,而您看不到该显示器。并且没有选项可以将图像从服务器的显示器重定向到您的显示器 - 到您显示器上的 Google Colaboratory 窗口。


如果您将在您的计算机上运行它,那么您将看不到 Chrome,因为您使用了"--headless"表示“不显示窗口”的选项。它经常用在服务器上,因为服务器通常没有监视器(服务器被称为“无头服务器”,因为监视器看起来像计算机的头部),用户看不到这个监视器。

使用选项"--headless"Chrome 不必渲染和显示页面,因此它也可以更快地工作。即使在本地计算机上,此选项也很有用。


推荐阅读