首页 > 解决方案 > 如何使用 docker-compose 将 selenium webdriver 中的文件保存在容器中?

问题描述

我尝试使用 selenium 和 docker-compose 从站点保存相同的文件。当我在下载文件的链接上执行 .click() 时,它保存在容器 /home/seluser/Downloads 中,但是当我尝试挂载值以将文件保存在主机中时:-./app/down:/home/seluser/Downloads
它只会删除 selenium 容器中的文件夹 Downloads 中的所有内容,并且在程序运行时,容器 /home/seluser/Downloads 中不会出现任何文件,但如果没有定义卷,所有文件都会正常出现在 conainer 中。

alex@alex-Aspire-E1-571G:~/documents/python/yahoo_script/app$ docker ps
CONTAINER ID   IMAGE                        COMMAND                  CREATED          STATUS          PORTS                                       NAMES
aebf66508644   yahoo_script_app             "sh -c 'python3 main…"   32 seconds ago   Up 28 seconds                                               yahoo_script_app_1
16ad4ae3ddb0   selenium/standalone-chrome   "/opt/bin/entry_poin…"   34 seconds ago   Up 31 seconds   0.0.0.0:4444->4444/tcp, :::4444->4444/tcp   yahoo_script_selenium_1
alex@alex-Aspire-E1-571G:~/documents/python/yahoo_script/app$ docker exec -it 16 /bin/sh
$ cd home/seluser/Downloads
$ ls
PD.csv  PINS.csv  ZUO.csv

我的 Dockerfile:

FROM python:3.8
ENV PYTHONUNBUFFERED 1
RUN pip install --upgrade pip
COPY ./requirements.txt /requirements.txt
RUN pip install -r /requirements.txt
COPY ./app /app
WORKDIR /app

我的 docker-compose.yml

version: "3"

services:
  selenium:
    image: selenium/standalone-chrome
    volumes:
      - ./app/down:/home/seluser/Downloads
    ports:
    - 4444:4444
    restart: always

  app:
    build:
      context: .
    volumes:
    - ./app:/app
    command: sh -c "python3 main.py"
    depends_on:
      - selenium

和代码:

    options = webdriver.ChromeOptions()
    options.headless = True
    options.add_argument("--no-sandbox")
    options.add_argument('--disable-blink-features=AutomationControlled')
    prefs = {'download.default_directory': f'/home/seluser/Downloads',
             "directory_upgrade": True,
             "safebrowsing.enabled": True
             }
    options.add_experimental_option('prefs', prefs)
    capabilities = {
        "browserName": "chrome",
        "version": "90.0.4430.85",
        "platform": "LINUX"
    }
    driver = webdriver.Remote('http://selenium:4444/wd/hub', desired_capabilities=capabilities, options=options)

如何将文件从容器传输到主机?

标签: pythonseleniumfiledocker-composesave

解决方案


我发现 Prompt_for_download 中的答案在 prefs 中设置 false 后仍然出现 主要是什么
Aside from that, make sure directory exists and there are permissions to write into it.


推荐阅读