美文网首页
Linux下制作docker镜像,用于执行selenium模块,

Linux下制作docker镜像,用于执行selenium模块,

作者: for笑 | 来源:发表于2022-10-26 13:27 被阅读0次

制作selenium+chromium 的 docker 镜像,并设置中文支持(思源黑体 SourceHanSansCN-Normal.otf 可以从这里下载 https://github.com/adobe-fonts/source-han-sans/releases/download/2.004R/SourceHanSansCN.zip)

制作好的镜像中执行

fc-list :lang=zh 查看字体

chromium-browser --version 查看chrome版本

chromedriver --version 查看驱动版本

python --version 查看python版本

pip list 查看python模块版本

apk --version apk包管理工具

docker build -t 'selenium-chrome:latest . (默认当前目录下的Dockerfile 文件)

docker build -t 'selenium-chrome:latest -f ./selenium-chrome .    (-f 指定dockerfile文件名)

Dockerfile

FROM python:3.8.8-alpine3.13 AS build

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \

    apk update && \

    apk add --no-cache gcc libffi-dev musl-dev && \

    pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \

    pip install -U pip &&\

    pip install --timeout 30 --user --no-cache-dir --no-warn-script-location selenium

FROM python:3.8.8-alpine3.13

ENV LOCAL_PKG="/root/.local"

COPY --from=build ${LOCAL_PKG} ${LOCAL_PKG}

COPY SourceHanSansCN-Normal.otf /usr/share/fonts/

RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \

    apk update && \

    apk add --no-cache xvfb-run chromium chromium-chromedriver && \

    ln -sf ${LOCAL_PKG}/bin/* /usr/local/bin/

RUN mkdir /data

WORKDIR /data

安装gcc libffi-dev musl-dev 这3个包,是安装 selenium 需要的依赖包。selenium 安装到 /root/.local 这目录。

重新打包,然后使用上一个打包的 /root/.local 目录复制到新的镜像里面,然后安装 xvfb-run chromium chromium-chromedriver。xvfb-run 是为了在容器无图形界面的情况下调用有图形界面的浏览器而使用的。

启动容器执行python脚本

xvfb-run --server-args="-screen 0 1920x1080x16" python baidu_script.py

baidu_script.py

import time

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

options = Options()

options.add_argument("--no-sandbox")

options.add_argument("window-size=1920,1080")

driver=webdriver.Chrome(options=options)

driver.get('http://www.baidu.com/')

title=driver.title

print(title)

driver.save_screenshot('screenshot.png')

driver.close()

相关文章

网友评论

      本文标题:Linux下制作docker镜像,用于执行selenium模块,

      本文链接:https://www.haomeiwen.com/subject/tjvazrtx.html