如何部署使用Python模块的Shiny应用并安装ChromeDriver
问题1:正确部署依赖Python模块的Shiny应用
- 第一步:整理Python依赖
在Shiny应用根目录(和app.R同级)新建requirements.txt文件,写入所有第三方Python依赖:
注:pandas selenium urllib3 webdriver-managertime、re属于Python标准库,无需额外声明 - 第二步:放置自定义模块
将你开发的scrapeinsolvencyinsider.py文件放在应用根目录,确保和app.R同层级。 - 第三步:修改app.R中的reticulate配置
删除当前动态创建虚拟环境的代码,替换为如下配置,避免每次启动重复创建环境、路径匹配错误的问题:
你之前触发# 最开头先配置reticulate环境 Sys.setenv(RETICULATE_PYTHON = "python3") library(reticulate) # 仅当虚拟环境不存在时创建,避免重复安装 if (!virtualenv_exists("statcanEnv")) { virtualenv_create(envname = "statcanEnv", python_version = "3.8") virtualenv_install("statcanEnv", packages = readLines("requirements.txt")) } use_virtualenv("statcanEnv", required = TRUE) # 把当前应用目录加入Python搜索路径,解决自定义模块找不到的问题 py_run_string("import sys; sys.path.insert(0, '.')") # 导入自定义模块 sii <- import("scrapeinsolvencyinsider") # 后面再加载其他R包 library(shiny) library(tidyverse) library(DescTools) library(lubridate) library(googlesheets4)ModuleNotFoundError的核心原因有两个:一是没有把应用根目录加入Python搜索路径,Python找不到你的自定义模块;二是每次启动重复创建虚拟环境,容易出现环境未激活就导入模块的时序问题。
问题2:shinyapps.io平台安装Chrome与ChromeDriver
shinyapps.io的运行环境为Ubuntu系统,无图形界面,不需要手动下载ChromeDriver,按如下步骤配置即可:
- 第一步:安装Chrome浏览器
在app.R最开头加入系统命令,启动时自动安装Chrome:# 安装Chrome浏览器(仅首次运行执行) if (!file.exists("/usr/bin/google-chrome")) { system("wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb") system("sudo dpkg -i google-chrome-stable_current_amd64.deb") system("sudo apt-get install -f -y") } - 第二步:Python代码中自动匹配ChromeDriver
在你的scrapeinsolvencyinsider.py中,使用webdriver-manager自动获取对应版本的ChromeDriver,同时开启无头模式适配无图形界面的环境:
不需要手动下载ChromeDriver放到指定路径,from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service chrome_options = Options() # 必须开启的无头配置 chrome_options.add_argument("--headless=new") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-gpu") # 自动安装匹配版本的ChromeDriver driver = webdriver.Chrome( service=Service(ChromeDriverManager().install()), options=chrome_options )webdriver-manager会自动处理版本匹配和路径配置。
内容的提问来源于stack exchange,提问作者BigBossRob
相关产品推荐
相关产品推荐

