如何在shinyapps.io部署的Shiny应用中使用RSelenium包?
解决shinyapps.io部署RSelenium应用时phantomJS报错的问题
核心原因
phantomJS相关的phantomjs包已从CRAN下架,且shinyapps.io服务器环境不再维护phantomJS支持,因此依赖它的RSelenium默认配置会触发报错。
解决方案:改用Chrome无头浏览器
shinyapps.io服务器预装了Chrome浏览器和对应版本的chromedriver,直接调整RSelenium的启动配置即可解决问题:
- 修改RSelenium初始化代码
替换原来依赖phantomJS的rsDriver调用,改用Chrome无头模式:
library(RSelenium) # 配置Chrome无头启动参数 chrome_config <- list( chromeOptions = list( args = c( '--headless', # 无头模式,不显示浏览器界面 '--no-sandbox', # 绕过沙箱限制(服务器环境必需) '--disable-dev-shm-usage', # 解决服务器内存不足问题 '--disable-gpu' # 禁用GPU加速,避免无头模式兼容性问题 ) ) ) # 启动Chrome驱动 driver <- rsDriver( browser = "chrome", chromever = "latest", # 自动匹配服务器上的Chrome版本 extraCapabilities = chrome_config ) # 后续操作保持原有逻辑 remDr <- driver[["client"]] remDr$navigate("https://example.com")
- 清理无效依赖
- 删除代码中所有尝试安装
phantomjs的语句(包括webshot::install_phantomjs()这类) - 确保应用的依赖声明(如
DESCRIPTION或renv.lock)中不包含phantomjs包,仅保留RSelenium
- 版本匹配排查
如果启动时报chromedriver版本不匹配,可先查看shinyapps.io服务器上的Chrome版本,再指定对应版本的chromever:
# 示例:服务器Chrome版本为114.0.5735.90,对应chromedriver版本相同 driver <- rsDriver(browser = "chrome", chromever = "114.0.5735.90", extraCapabilities = chrome_config)
替代方案:直接调用Selenium Server
如果rsDriver仍有问题,可直接启动Selenium Server并连接远程驱动:
library(RSelenium) # 启动Selenium Server(shinyapps.io预装了对应jar包) sel_server <- wdman::selenium(jvmargs = c("-Dwebdriver.chrome.whitelistedIps=''")) # 连接Chrome远程驱动 remDr <- remoteDriver( remoteServerAddr = "localhost", port = 4444L, browserName = "chrome", extraCapabilities = list(chromeOptions = list(args = c('--headless', '--no-sandbox'))) ) remDr$open()
内容的提问来源于stack exchange,提问作者user1713174
相关产品推荐
相关产品推荐

