在Github Actions中运行RSelenium作业时无法找到chromedriver的解决方法
解决GitHub Actions中RSelenium找不到Chrome驱动的问题
问题背景
本地Windows机器上使用RSelenium的动态网页抓取脚本运行正常,但部署到GitHub Actions时,出现binman::list_versions("chromedriver")报错,提示~/Library/Application Support/binman_chromedriver app directory not found。这是因为GitHub Actions的Ubuntu虚拟机默认没有预装Chrome及对应驱动,且Linux环境下binman的默认存储路径与Windows不同。
修改方案
1. 调整GitHub Actions工作流配置,安装Chrome和ChromeDriver
在你的Workflow文件(通常是.github/workflows/xxx.yml)中,添加Chrome安装步骤,使用官方维护的action自动匹配Chrome和驱动版本:
jobs: scrape-job: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: 配置R环境 uses: r-lib/actions/setup-r@v2 with: r-version: '4.3.1' # 替换为你实际使用的R版本 - name: 安装R依赖包 run: | install.packages(c("data.table", "rvest", "RSelenium", "binman")) - name: 安装Chrome及ChromeDriver uses: browser-actions/setup-chrome@v1 with: chrome-version: stable - name: 运行抓取脚本 run: Rscript -e 'source("R/job.R", echo = TRUE)'
该action会自动处理Chrome和驱动的安装,并配置好环境变量,让RSelenium能直接调用。
2. 修改R脚本中的驱动初始化代码
GitHub Actions是无头环境,必须启用Chrome的无头模式,同时直接使用系统安装的驱动,避免依赖binman自动下载:
library(data.table) library(rvest) library(RSelenium) Sys.setenv(TZ = "Australia/Sydney") # 初始化Chrome驱动,启用无头模式 driver <- rsDriver( browser = "chrome", chromever = "latest", extraCapabilities = list( chromeOptions = list( args = c("--headless", "--no-sandbox", "--disable-dev-shm-usage") ) ) ) remDr <- driver[["client"]] # 后续的抓取代码... # 最后记得关闭驱动 remDr$close() driver$server$stop()
--headless:无图形界面虚拟机运行Chrome的必填参数--no-sandbox:解决Linux环境下的权限限制问题--disable-dev-shm-usage:避免虚拟机临时内存不足的问题
3. (可选)修复binman路径问题
如果仍遇到binman路径错误,可在脚本开头手动指定其存储目录:
Sys.setenv(BINMAN_ROOT = file.path(Sys.getenv("HOME"), ".local/share/binman"))
不过使用上述Workflow配置安装Chrome后,一般不需要这一步。
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

