实现同步博客文章到github首页

cccs7 Lv5

需求: 将个人博客最近的几篇文章同步到 github 首页的指定区域

image-20230704154959850

在GitHub上面创建一个同名仓库,比如我的id为cs7eric,我就创建一个仓库名为cs7eric的仓库,里面的README会直接在个人Github首页渲染展示。

想让首页自动更新个人博客园上面的文章链接,可以使用GitHub自带的CI工具GitHub Actions

总体的思路:

  • 用Python爬取个人博客的文章链接
  • 编写GitHub Actions的配置脚本

使用 Python 爬取个人博客的文章

1
2
3
4
5
<h3 class="home-article-title">
<a href="/2023/07/03/less/" data-pjax-state="">
less
</a>
</h3>

这是我个人博客文章的HTML结构,上面框里面的内容是我们想要的信息。

借助Python里面的BeautifulSoup库,可以快速地将这些信息提取出来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import requests
from bs4 import BeautifulSoup

# 博客网站的 URL
url = "https://blog.cccs7.icu/"

# 发送 GET 请求获取 HTML 页面
response = requests.get(url)

# 使用 BeautifulSoup 解析 HTML 页面
soup = BeautifulSoup(response.text, "html.parser")

# 获取最新的7篇文章的标题和链接
articles = soup.find_all("h3", class_="home-article-title")[:5]
article_list = [f"- [{article.text.strip()}]({url + article.find('a', href=True)['href']})\n" for article in articles]

# 读取现有的README.md文件
with open("README.md", "r", encoding="utf-8") as f:
lines = f.readlines()

# 找到要添加新文章的位置
start_index = 55
end_index = 60

# 将新的文章添加到指定位置
new_lines = lines[:start_index] + article_list + lines[end_index:]
with open("README.md", "w", encoding="utf-8") as f:
f.writelines(new_lines)

python 脚本如上

编写 actions 配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
name: Sync Blog Posts to GitHub Pages
on:
schedule:
- cron: "0 0 * * *"
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: "3.9"

- name: Install Dependencies
run: |
pip install beautifulsoup4 requests

- name: Sync Blog Posts
run: |
python sync_blog_posts.py

- name: Commit Changes
run: |
git config --global user.email "csq020611@gmail.com"
git config --global user.name "cs7eric"
git add -A
git commit -m "Sync blog posts"

- name: Push Changes
uses: ad-m/github-push-action@v0.6.0
with:
repository: cs7eric/cs7eric
branch: main
github_token: ${{ secrets.FOR_ACTIONS }}

github workflow 配置

image-20230704155950699

将之前的 python 脚本放在仓库根目录下,将 action 配置文件添加到 .github/workflows 下,运行 workflows 测试

image-20230704160142799

  • Title: 实现同步博客文章到github首页
  • Author: cccs7
  • Created at : 2023-07-04 15:20:22
  • Updated at : 2024-09-13 11:07:59
  • Link: https://cs7eric.github.io/2023/07/04/实现同步博客文章到github首页/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments