我们如何在 colab.research.google.com 中使用 Selenium Webdriver?

How can we use Selenium Webdriver in colab.research.google.com?

我想在 colab.research.google.com 中使用 Chrome 的 Selenium Webdriver 进行快速处理。我能够使用 !pip install selenium 安装 Selenium,但是 chrome 的网络驱动程序需要 webdriverChrome.exe 的路径。我应该如何使用它?

P.S.- colab.research.google.com 是一个在线平台,为与深度学习相关的快速计算问题提供 GPU。请避免使用 webdriver.Chrome(path) 之类的解决方案。

您可以使用 WebDriverManager 来摆脱使用 .exe 文件,而不是这个

System.setProperty("webdriver.gecko.driver", "driverpath/.exe");
WebDriver driver = new FirefoxDriver();

你会写这个

WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();

你只需要将依赖项添加到 POM 文件(我假设你使用 Maven 或一些构建工具) 请在 link 中查看我关于如何使用它的完整答案

您可以通过安装 chromium webdriver 并调整一些选项使其不会在 google colab 中崩溃:

!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
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://www.webite-url.com")

这个在 colab 中工作

!pip install selenium
!apt-get update 
!apt install chromium-chromedriver

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')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)

为了方便起见,我制作了自己的库。

!pip install kora -q
from kora.selenium import wd
wd.get("https://www.website.com")

PS:我忘记了我是如何搜索和试验直到它起作用的。但我在 2018 年 12 月 this gist 中首次撰写并分享了它。

没有足够的信誉来发表评论。 :(

然而,@Thomas 的回答在 2021 年 10 月 6 日仍然有效,但只需进行一个简单的更改,您就会得到 DeprecationWarning: use options instead of chrome_options

下面的工作代码:

!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',options=options)
wd.get("
wd.title

在 GOOGLE COLAB 中使用 selenium 在 colab notebook 中执行后续步骤

!pip install kora -q

如何在 COLAB 中使用它:

from kora.selenium import wd
wd.get("enter any website here")

您还可以将它与 Beautiful Soup 一起使用

import bs4 as soup
wd.get("enter any website here")
html = soup.BeautifulSoup(wd.page_source)