在AWS Lambda上使用Python 3.6运行Headless Chrome-权限错误

时间:2018-08-27 21:12:21

标签: python-3.x selenium aws-lambda selenium-chromedriver google-chrome-headless

我一直在努力让Headless Chrome在AWS Lambda上运行几天。它在EC2上可以正常工作,但是当我在Lambda上尝试时,我只得到"Message: 'chromedriver' executable may have wrong permissions.

在zip文件的根目录中,使用chromedriver和headless-chromium可执行文件压缩模块。我上传到S3的压缩文件总数为52mb,但提取的文件数低于250mb的限制,因此我认为这不是问题。

Python Zip Folder Structure Image

from selenium import webdriver


def lambda_handler(event, context):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")
    options.add_argument("--window-size=1280x1696")
    options.add_argument("--disable-application-cache")
    options.add_argument("--disable-infobars")
    options.add_argument("--no-sandbox")
    options.add_argument("--hide-scrollbars")
    options.add_argument("--enable-logging")
    options.add_argument("--log-level=0")
    options.add_argument("--v=99")
    options.add_argument("--single-process")
    options.add_argument("--ignore-certificate-errors")
    options.add_argument("--homedir=/tmp")
    options.binary_location = "/var/task/headless-chromium"

    driver = webdriver.Chrome("/var/task/chromedriver", chrome_options=options)
    driver.get("https://www.google.co.uk")
    title = driver.title
    driver.close()

    return title


if __name__ == "__main__":
    title = lambda_handler(None, None)
    print("title:", title)

网络上的一些帖子报告了兼容性问题,可能会引起问题,因此我从网络上获得了适用于Chrome和ChromeDriver的特定可执行版本,其他版本似乎都在以前的EC2和其他方面取得了成功。

无头铬钢和铬木矿工的下载资源 (稳定)https://github.com/adieuadieu/serverless-chrome/releases/tag/v1.0.0-37https://sites.google.com/a/chromium.org/chromedriver/downloads)无法下载,因此可从下面的源中检索 https://chromedriver.storage.googleapis.com/index.html?path=2.37/

有人可以帮我破解吗?

1 个答案:

答案 0 :(得分:1)

几分钟前,我找到了解决此问题的方法。 在Lambda Function中使用chromedriver时(我认为),需要写权限。但是当chrome驱动程序文件位于“任务”文件夹或“选择”文件夹中时,用户只能拥有读取权限。

在Lambda函数中,只有文件夹可以更改权限。功能是'tmp'文件夹。

因此,我将chrome驱动程序文件移至“ tmp”文件夹。而且有效。

像这样

os.system("cp ./chromedriver /tmp/chromedriver")
os.system("cp ./headless-chromium /tmp/headless-chromium")
os.chmod("/tmp/chromedriver", 0o777)
os.chmod("/tmp/headless-chromium", 0o777)
chrome_options.binary_location = "/tmp/headless-chromium"
driver = webdriver.Chrome(executable_path=r"/tmp/chromedriver",chrome_options=chrome_options)