1,在github
里创建项目,例如yxip
2,在项目yxip
里创建文件collect_ips.py
,填入以下内容
import requests
from bs4 import BeautifulSoup
import re
import os
# 目标URL列表
urls = ['https://monitor.gacjie.cn/page/cloudflare/ipv4.html',
'https://ip.164746.xyz'
]
# 正则表达式用于匹配IP地址
ip_pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
# 检查ip.txt文件是否存在,如果存在则删除它
if os.path.exists('ip.txt'):
os.remove('ip.txt')
# 创建一个文件来存储IP地址
with open('ip.txt', 'w') as file:
for url in urls:
# 发送HTTP请求获取网页内容
response = requests.get(url)
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 根据网站的不同结构找到包含IP地址的元素
if url == 'https://monitor.gacjie.cn/page/cloudflare/ipv4.html':
elements = soup.find_all('tr')
elif url == 'https://ip.164746.xyz':
elements = soup.find_all('tr')
else:
elements = soup.find_all('li')
# 遍历所有元素,查找IP地址
for element in elements:
element_text = element.get_text()
ip_matches = re.findall(ip_pattern, element_text)
# 如果找到IP地址,则写入文件
for ip in ip_matches:
file.write(ip + '\n')
print('IP地址已保存到ip.txt文件中。')
3,在项目yxip
里创建.github/workflows/main.yml
文件,填入以下内容
name: Update IP List
on:
schedule:
- cron: '*/45 * * * *' # 每45分钟更新一次
workflow_dispatch:
push:
jobs:
update-ip-list:
runs-on: ubuntu-latest
permissions:
contents: write # 写入权限必须保留
steps:
# 关键修改点1:带token检出
- uses: actions/checkout@v3
with:
token: ${{ secrets.GITHUB_TOKEN }} # 注入认证信息
fetch-depth: 0 # 获取完整提交历史
# 关键修改点2:先同步最新代码
- name: Pre-sync repository
run: |
git config --global user.email "[email protected]"
git config --global user.name "tianshipapa"
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/camel52zhang/yxip.git
git pull origin main # 普通拉取最新代码
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install requests beautifulsoup4
- name: Run script
run: python ${{ github.workspace }}/collect_ips.py
# 关键修改点3:智能提交逻辑
- name: Commit and push changes
run: |
# 检测文件变化
if [ -n "$(git status --porcelain -- ip.txt)" ]; then
git add ip.txt
git commit -m "Automatic update: $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
# 带重试的推送机制
for i in {1..3}; do
git pull --rebase origin main && break || sleep 5
done
git push origin HEAD:main
echo "✅ 更新推送成功"
else
echo "🔄 未检测到IP变化"
fi
至此完成了从https://monitor.gacjie.cn/page/cloudflare/ipv4.html
和https://ip.164746.xyz
获取有些IP的目的,优选的IP保存在ip.txt
文件里
假如感觉45分钟执行一次太频繁,可以按以下修改schedule
schedule:
- cron: '3 1,13 * * *' # 每天UTC 1:03和13:03
workflow_dispatch: # 保留手动触发