2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS Lambda+Selenium(python)でダウンロード場所を、/tmpに変更する方法

Posted at

問題

 Selniumを使用して特定のサイトからファイルをダウンロードするアプリケーションを作成し、AWS Lambdaにデプロイする際、問題が発生する。

 ダウンロードディレクトリが作業ディレクトリと一致しない

 ということだ。

ダウンロード先を/tmpに指定する

作業ディレクトリであるtmpにダウンロード先を指定する方法は、様々な海外サイトなどに掲載されているが、2023年8月現在、うまく動かなかったので、うまくいった方法を示す。

python
def startupchrome():
    #オプションの追加を行う
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument("--no-sandbox")
    options.add_argument("--single-process")
    options.add_argument("--disable-dev-shm-usage")
    
    #ダウンロードする場所の変更
    prefs = {"browser.downloads.dir": "//tmp//", "download.default_directory": "//tmp//", "directory_upgrade": True}
    options.add_experimental_option("prefs", prefs)
    
    options.binary_location = "/opt/headless/python/bin/headless-chromium"

    #ブラウザの定義
    browser = webdriver.Chrome(
        "/opt/headless/python/bin/chromedriver",
        options=options
    )
    
    browser.command_executor._commands["send_command"] = (
        "POST",
        "/session/$sessionId/chromium/send_command",
    )
    
    params = {
        "cmd": "Page.setDownloadBehavior",
        "params": {"behavior": "allow", "downloadPath": '/tmp'},
    }
    
    data = browser.execute("send_command", params)
    
    return browser

この関数はseleniumのdriverを返却する。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?