谷歌的硒 Colab

时间:2021-06-28 19:15:57

标签: python selenium selenium-webdriver selenium-chromedriver google-colaboratory

我在 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://ca.yahoo.com")

我收到以下错误:

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:12: DeprecationWarning: use options instead of chrome_options
  if sys.path[0] == '':

所以我通过从 chrome_options 中删除 chrome 来更改代码:

# !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("https://ca.yahoo.com")

然后当我再次运行它时,我什么也没得到。我预计浏览器会启动并加载雅虎。但是……没什么……?

请帮忙。在此先感谢您。

干杯

1 个答案:

答案 0 :(得分:0)

您正在尝试更改变量名称。这不是问题!
您应该使用不同的导入。
你的代码应该是这样的:

import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
from selenium.webdriver.chrome.options import Options #This is what you should add!
options = Options()
options.headless = True
wd = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)
wd.get("https://ca.yahoo.com")

请注意,在 webdriver.Chrome(CHROMEDRIVER_PATH, options=options) 中,第一个参数是 chromedriver 可执行文件的路径,而不仅仅是字符串“chromedriver”