如何从Google Sheet调用含Selenium的Python自动化脚本执行?
解决方案
本地触发方案(优先推荐,无需云服务)
核心思路是通过Google Apps Script向本地运行的Python服务发送请求,触发Selenium脚本执行:
给Google Sheet添加触发菜单
打开Sheet的「扩展程序」→「Apps Script」,写入以下代码创建自定义菜单,点击后发送HTTP请求到本地服务:function onOpen() { const ui = SpreadsheetApp.getUi(); ui.createMenu('自动化工具') .addItem('启动下载脚本', 'triggerScript') .addToUi(); } function triggerScript() { // 替换为你的本地服务地址,例如http://localhost:5000/run-script const url = 'http://你的本地IP:5000/run-script'; try { UrlFetchApp.fetch(url, {method: 'POST'}); SpreadsheetApp.getUi().alert('脚本已触发执行'); } catch (e) { SpreadsheetApp.getUi().alert('触发失败:' + e.message); } }保存后刷新Sheet,顶部会出现「自动化工具」菜单,点击即可发起触发请求。
本地运行Python监听服务
用Flask写一个简单的HTTP服务,收到请求后调用你的Selenium脚本:from flask import Flask import subprocess app = Flask(__name__) @app.route('/run-script', methods=['POST']) def run_script(): # 替换为你的Selenium脚本绝对路径 subprocess.run(['python', 'path/to/your/selenium_script.py']) return '脚本执行中', 200 if __name__ == '__main__': # 允许同一局域网设备访问,端口可自定义 app.run(host='0.0.0.0', port=5000, debug=True)运行该Flask服务后,确保Sheet和你的电脑在同一网络下;若需外网触发,可使用内网穿透工具临时暴露本地端口。
云服务方案(可选)
如果需要脱离本地环境运行,可使用Google Cloud Run部署带Chrome环境的Selenium服务:
打包Selenium脚本为Docker镜像
编写Dockerfile,包含Python、Chrome及ChromeDriver:FROM python:3.9-slim RUN apt-get update && apt-get install -y wget unzip chromium chromium-driver WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY your_selenium_script.py . CMD ["python", "your_selenium_script.py"]构建镜像并推送到Google Container Registry。
部署到Cloud Run
在Google Cloud Console创建Cloud Run服务,设置允许未验证调用(或通过IAM控制权限),然后修改Apps Script中的triggerScript函数,将请求地址替换为Cloud Run的服务地址,即可触发云端脚本执行。
注意事项
- 本地方案需保持监听服务处于运行状态,适合个人日常使用场景。
- 云方案需在Selenium脚本中配置Chrome无头模式(
options.add_argument('--headless=new')),避免UI交互异常。 - 确保Selenium脚本读取Google Sheet的权限配置正确(例如使用服务账号密钥)。
内容的提问来源于stack exchange,提问作者Tarun Aditya
相关产品推荐
相关产品推荐

