在 GitHub Actions 中使用 shot-scraper

shot-scraper 的设计初衷就考虑了用于屏幕截图自动化的 GitHub Actions。

shot-scraper-template

shot-scraper-template 模板仓库可用于快速创建您自己的 GitHub 仓库,并配置 GitHub Actions 来截取页面截图并将其写回仓库。阅读立即创建 GitHub 仓库以截取网页截图了解详情。

从零开始构建工作流程

此 Actions 工作流程可用于安装 shot-scraper 及其依赖项,截取该仓库中 shots.yml 文件定义的屏幕截图,然后将生成的屏幕截图写回同一仓库。

name: Take screenshots

on:
  push:
  workflow_dispatch:

permissions:
  contents: write

jobs:
  shot-scraper:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Set up Python 3.10
      uses: actions/setup-python@v3
      with:
        python-version: "3.10"
    - uses: actions/cache@v3
      name: Configure pip caching
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-pip
    - name: Cache Playwright browsers
      uses: actions/cache@v3
      with:
        path: ~/.cache/ms-playwright/
        key: ${{ runner.os }}-playwright
    - name: Install dependencies
      run: |
        pip install shot-scraper
        shot-scraper install
    - name: Take shots
      run: |
        shot-scraper multi shots.yml
    - name: Commit and push
      run: |-
        git config user.name "Automated"
        git config user.email "actions@users.noreply.github.com"
        git add -A
        timestamp=$(date -u)
        git commit -m "${timestamp}" || exit 0
        git pull --rebase
        git push

actions/cache@v3 步骤设置了缓存,因此您的工作流程只会在首次运行时下载并安装必要的软件。

使用 Oxipng 优化 PNG 文件

您可以通过运行 Oxipng 对使用 shot-scraper 生成的 PNG 文件进行无损压缩。将以下步骤添加到您的工作流程的开头以安装 Oxipng

    - name: Cache Oxipng
      uses: actions/cache@v3
      with:
        path: ~/.cargo/
        key: ${{ runner.os }}-cargo
    - name: Install Oxipng if it is not installed
      run: |
        which oxipng || cargo install oxipng

然后在运行 shot-scraper 后添加此步骤来压缩图片

    - name: Optimize PNGs
      run: |-
        oxipng -o 4 -i 0 --strip safe *.png

simonw/datasette-screenshots 是使用此模式的仓库示例。

参见在 GitHub Actions 中使用 Oxipng 优化 PNG 文件了解其工作原理。