docker中使用playwright

一.拉取镜像

  文档链接:https://playwright.dev/python/docs/docker#usage

docker pull mcr.microsoft.com/playwright/python:v1.35.0-focal

二.启动容器

     这边要注意限制容器日志的大小,要不然很容易把磁盘装满了,可参考:https://blog.csdn.net/weixin_44368081/article/details/124719119

docker run -tid --name 自己给容器起名字--log-opt max-size=10m --log-opt max-file=3 镜像id

三.修改时区

1.直接这个命令

tzselect

  设置完成后如提示

You can make this change permanent for yourself by appending the line
    TZ='Asia/Shanghai'; export TZ
to the file '.profile' in your home directory; then log out and log in again.

Here is that TZ value again, this time on standard output so that you
can use the /usr/bin/tzselect command in shell scripts:
Asia/Shanghai

  则执行下面命令

sudo ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

2.当1有问题的话,用这个(备用方案)

apt-get install tzdata

 

四.安装一些依赖

  1. vim 文件编辑器


apt update
apt search vim
apt install vim

     2.cron,这边安装好,记得把服务启动,容易重启后服务需要手动启动

安装:apt-get install cron
启动:service cron start
重启:service cron restart
停止:service cron stop
检查状态:service cron status
查询cron可用的命令:service cron
检查Cronta工具是否安装:crontab -l

 五.注意点

  1.正常使用官方的docker镜像,大部分依赖都会帮你安装好,可能还需要自己安装相应的包

pip install playwright

  2.有的时候你会发现正常执行命令如下,可以正常执行,但是定时任务执行会有问题

xvfb-run  --auto-servernum --server-num=1 python xxxxxx.py

  报错:Executable doesn't exist at /root/.cache/ms-playwright/firefox-1408/firefox/firefox

  原因是定时任务的环境变量和终端是不一样的,可以通过如下命令,来查看终端和定时任务的环境变量差异

printenv

  结果中可以看到PLAYWRIGHT_BROWSERS_PATH的值,但是用定时任务去找playwright的路径是user/.cache/ms-playwright/firefox-xxxx/firefox/firefox

root@xxxxx:~/xxx# printenv
HOSTNAME=xxxxx
PWD=/root/xxxx
HOME=/root
PLAYWRIGHT_BROWSERS_PATH=/ms-playwright

  解决方案:通过定时任务启动shell脚本

  crontab 的定时语句

55 19 * * *  cd /root/xxxx &&  sh /root/zhihu/start.sh > /dev/null 2>&1

  在shel脚本中把终端的PLAYWRIGHT_BROWSERS_PATH导入进来

#!/bin/bash

export PLAYWRIGHT_BROWSERS_PATH=/ms-playwright



nohup xvfb-run  --auto-servernum --server-num=1 python xxxx.py >/dev/null 2>error.log  2>&1 &

 

posted @ 2023-07-05 11:07  阿布_alone  阅读(705)  评论(0编辑  收藏  举报
TOP