You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda中Selenium无法定位ChromeDriver问题求助

解决AWS Lambda中Selenium Chrome驱动初始化失败问题

问题原因

Lambda运行环境(Amazon Linux 2)没有预装Chrome浏览器和对应版本的chromedriver,且Selenium v4的Selenium Manager在Lambda的受限环境下无法自动下载驱动和浏览器,导致报错Unable to obtain driver for chrome using Selenium Manager。

解决方案

需要手动打包兼容Lambda环境的Chrome浏览器、匹配版本的chromedriver,并配置正确的Selenium参数。

1. 准备必要文件

  • Headless Chrome浏览器:下载适配Amazon Linux 2的版本(推荐获取专为无服务器环境编译的headless-chromium)
  • chromedriver:下载与Chrome版本严格匹配的Linux版驱动程序
  • 将这两个文件添加到部署包根目录,本地执行chmod +x headless-chromium chromedriver赋予执行权限

2. 修改Lambda代码

调整Chrome配置,手动指定浏览器和驱动路径,适配Lambda无图形界面的环境:

import json
from bs4 import BeautifulSoup
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.common import exceptions
from time import sleep
import os

def lambda_handler(event, context):
    # 配置Chrome运行参数
    chrome_options = Options()
    chrome_options.add_argument("--headless=new")  # Selenium 4.10+推荐的无头模式
    chrome_options.add_argument("--no-sandbox")  # 禁用沙箱(Lambda环境无权限运行沙箱)
    chrome_options.add_argument("--disable-dev-shm-usage")  # 解决/dev/shm空间不足问题
    chrome_options.add_argument("--disable-gpu")  # 禁用GPU加速(无头环境不需要)
    chrome_options.add_argument("--window-size=1920x1080")  # 设置窗口大小
    
    # 获取部署包内的Chrome和驱动路径
    chrome_binary_path = os.path.join(os.getcwd(), "headless-chromium")
    chromedriver_path = os.path.join(os.getcwd(), "chromedriver")
    
    # 指定Chrome二进制文件位置
    chrome_options.binary_location = chrome_binary_path
    
    # 初始化驱动服务并启动Chrome
    driver_service = Service(executable_path=chromedriver_path)
    driver = Chrome(service=driver_service, options=chrome_options)
    
    # 示例操作:访问网页并打印标题
    try:
        driver.get("https://example.com")
        print(f"页面标题:{driver.title}")
    finally:
        driver.quit()  # 务必关闭驱动,避免资源泄漏
    
    return {"statusCode": 200, "body": json.dumps("操作完成")}

3. 部署注意事项

  • 如果部署包体积超过50MB(Chrome+驱动+依赖可能超限),建议将Chrome、chromedriver和依赖库(bs4、selenium等)放到Lambda层中,减少主函数包的大小
  • 确保所有文件权限正确,避免Lambda执行时出现权限不足的错误

内容的提问来源于stack exchange,提问作者slothish1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:30:00