在Google Colab中运行Selenium提示找不到Chrome二进制文件如何解决?
错误原因
你触发报错的核心原因是:你通过apt安装的是开源版本的Chromium浏览器,而非官方闭源的Google Chrome,因此/usr/bin/google-chrome路径不存在,导致webdriver找不到浏览器二进制文件。此外你代码里还有适配Windows系统的路径规则,和Colab的Linux环境不兼容。
需要修改的三处配置
- 调整/删除Windows格式的用户数据路径:
options.add_argument(r"user-data-dir=.\cookies\\test")是Windows系统的路径写法,Linux环境下不识别反斜杠和当前目录.的相对路径规则,如果你不需要持久化缓存cookies可以直接删除这行,需要的话可以改成你挂载的Google Drive路径,例如/content/gdrive/MyDrive/selenium_cookies/test - 修改浏览器二进制路径:将
options.binary_location = '/usr/bin/google-chrome'改为options.binary_location = '/usr/bin/chromium-browser' - (可选适配高版本Selenium)Selenium 4.0+版本不再推荐直接传入
executable_path参数,如果你使用高版本Selenium可以改用Service类指定驱动路径
完整可运行代码
首先运行前置依赖安装命令:
!apt-get update !apt install chromium-chromedriver !pip install selenium !cp /usr/lib/chromium-browser/chromedriver /usr/bin
然后运行修正后的业务代码:
import warnings warnings.filterwarnings('ignore') from bs4 import BeautifulSoup from selenium import webdriver from selenium.common.exceptions import InvalidSessionIdException from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from google.colab import drive drive.mount('/content/gdrive', force_remount=True) options = webdriver.ChromeOptions() options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument('--ignore-certificate-errors-spki-list') options.add_argument('--ignore-ssl-errors') options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) options.add_argument("--no-sandbox") options.add_argument("--disable-setuid-sandbox") options.add_argument("--disable-dev-shm-using") options.add_argument("--disable-extensions") options.add_argument("--disable-gpu") options.add_argument("start-maximized") options.add_argument("disable-infobars") # 如果你需要持久化cookies取消下一行注释,改成你自己的Drive路径即可 # options.add_argument(r"user-data-dir=/content/gdrive/MyDrive/selenium_cookies/test") options.binary_location = '/usr/bin/chromium-browser' # 低版本Selenium可以用原写法 driver = webdriver.Chrome(options=options, executable_path='/usr/bin/chromedriver') # 高版本Selenium用下面的写法,需要先导入Service:from selenium.webdriver.chrome.service import Service # driver = webdriver.Chrome(service=Service('/usr/bin/chromedriver'), options=options) driver.implicitly_wait(5) print("Current session is {}".format(driver.session_id))
内容的提问来源于stack exchange,提问作者PSCM
相关产品推荐
相关产品推荐

