Github Actions运行代码并发布到Pages上

• 4 分钟阅读 • web · linux

前文生成了python代码爬取豆瓣电影信息,得到静态页面,可以创建一个 GitHub Actions 工作流,自动运行 Python 脚本抓取数据,并生成 HTML 页面,然后将其部署到 GitHub Pages 上。

准备GitHub仓库

requests
beautifulsoup4

创建 GitHub Actions 工作流

在项目根目录创建 .github/workflows/deploy.yml,内容如下:

name: Deploy Douban Movies

on:
  schedule:
    - cron: '0 16 * * *'  # 北京时间每天0点(UTC 16:00)
  workflow_dispatch:      # 允许手动触发
  push:
    branches: [ main ]   # 推送时触发

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: write    # 必需:写入权限

    steps:
      # 步骤1:检出代码
      - name: Checkout
        uses: actions/checkout@v4

      # 步骤2:设置Python环境
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.10"

      # 步骤3:安装依赖
      - name: Install dependencies
        run: |
          pip install -r requirements.txt
          pip install pytz  # 时区支持

      # 步骤4:运行爬虫脚本(生成HTML)
      - name: Generate HTML
        run: python main.py

      # 步骤5:部署到GitHub Pages
      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs       # 推荐使用子目录
          publish_branch: gh-pages      # 部署到gh-pages分支
          force_orphan: true  # 确保分支干净     

建立gh-pages分支并修改文件生成路径

python脚本生成的html文件换到docs子目录下。
导入import os

def save_html(html_content, filename="docs/douban_movies.html"):
    os.makedirs("docs", exist_ok=True)
    with open(filename, "w", encoding="utf-8") as f:
        f.write(html_content)

新建gh-pages分支。

启用 GitHub Pages

进入仓库的 Settings > Pages。
选择 部署来源 为 GitHub Actions。

手动触发首次运行

提交代码后,进入 Actions 标签页。
选择 Deploy Douban Movies 工作流,点击 Run workflow 手动触发。

访问生成的页面

工作流运行完成后,访问:
https://<GitHub用户名>.github.io/douban-movies-nowplaying/douban_hot_movies.html
示例(html文件名改成了index.html):
https://qs100371.github.io/douban-movies-nowplaying/index.html
最终效果:

还有,数据生成时间是按utc得来的,和东8区差8个小时,ds也给出了修改方法。

from datetime import datetime
def get_beijing_time():
    tz = pytz.timezone('Asia/Shanghai')
    return datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')

# 在生成HTML时使用
update_time = get_beijing_time()

详细代码:qs100371/douban-movies-nowplaying

文章标签: web, linux

上一篇 : 安装alist
下一篇 : 豆瓣热映电影网页生成器
留言
阅读进度 0%