用脚本自动更换头像怎么做

wen 实用脚本 2

本文目录导读:

用脚本自动更换头像怎么做

  1. 方案一:网页自动化脚本(Python + Selenium)
  2. 方案二:GitHub Actions 定时更换
  3. 方案三:本地脚本 + Windows任务计划程序
  4. 方案四:Telegram机器人定时换头像
  5. 注意事项
  6. 浏览器扩展方案(如需要)

网页自动化脚本(Python + Selenium)

适用于自动更换社交平台(如微博、知乎等)头像。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import os
# 初始化浏览器
driver = webdriver.Chrome()
def change_avatar(website, login_info, avatar_path):
    """通用头像更换函数"""
    driver.get(website)
    # 登录(以微博为例)
    time.sleep(3)
    driver.find_element(By.ID, 'loginname').send_keys(login_info['username'])
    driver.find_element(By.ID, 'password').send_keys(login_info['password'])
    driver.find_element(By.CLASS_NAME, 'btn_submit').click()
    # 进入个人设置页面
    time.sleep(5)
    driver.find_element(By.LINK_TEXT, '账号设置').click()
    # 点击更换头像按钮
    time.sleep(3)
    driver.find_element(By.CSS_SELECTOR, '.change-avatar-btn').click()
    # 上传新头像文件
    upload_input = driver.find_element(By.CSS_SELECTOR, 'input[type="file"]')
    upload_input.send_keys(avatar_path)
    # 确认上传
    time.sleep(3)
    driver.find_element(By.CSS_SELECTOR, '.save-avatar-btn').click()
    print(f"头像已更换为: {os.path.basename(avatar_path)}")
    time.sleep(5)
# 批量更换示例
avatars = ['/path/avatar1.jpg', '/path/avatar2.jpg', '/path/avatar3.jpg']
for avatar in avatars:
    change_avatar(
        website='https://weibo.com',
        login_info={'username': 'your_username', 'password': 'your_password'},
        avatar_path=avatar
    )
    time.sleep(60)  # 避免频繁操作触发风控
driver.quit()

GitHub Actions 定时更换

适用于GitHub个人资料头像自动更新

创建Python脚本 update_avatar.py

import requests
import base64
import os
def update_github_avatar(token, image_path):
    headers = {
        'Authorization': f'token {token}',
        'Accept': 'application/vnd.github.v3+json'
    }
    # 获取当前用户信息
    user_resp = requests.get('https://api.github.com/user', headers=headers)
    user = user_resp.json()
    # 读取并编码图片
    with open(image_path, 'rb') as f:
        image_data = base64.b64encode(f.read()).decode()
    # 更新头像(GitHub需要先上传到临时位置)
    upload_url = 'https://api.github.com/user/emails'
    # 实际头像更新需要通过 https://github.com/settings/avatar 手动或使用桌面客户端
    print(f"用户: {user['login']},准备更新头像")
# 示例:随机选择一张本地图片
import glob
import random
avatars = glob.glob('./avatars/*.jpg')
chosen = random.choice(avatars)
update_github_avatar(
    token=os.environ['GITHUB_TOKEN'],
    image_path=chosen
)

创建GitHub Actions工作流 .github/workflows/update-avatar.yml

name: Update Avatar Daily
on:
  schedule:
    - cron: '0 0 * * *'  # 每天UTC中午12点
  workflow_dispatch:  # 允许手动触发
jobs:
  update-avatar:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'
      - name: Install dependencies
        run: pip install requests python-telegram-bot
      - name: Run avatar update
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: python update_avatar.py
      - name: Commit new avatar
        run: |
          git config --local user.name "GitHub Action"
          git config --local user.email "action@github.com"
          git add avatars/
          git commit -m "更新头像 $(date +%Y-%m-%d)" || echo "无变化"
          git push

本地脚本 + Windows任务计划程序

import os
import random
import shutil
from datetime import datetime
def rotate_avatars(avatar_dir, target_dir):
    """随机选择头像并复制为目标文件"""
    avatars = [f for f in os.listdir(avatar_dir) if f.lower().endswith(('.jpg', '.png'))]
    if not avatars:
        print("没有找到头像文件")
        return
    # 随机选择一张
    chosen = random.choice(avatars)
    source = os.path.join(avatar_dir, chosen)
    target = os.path.join(target_dir, 'avatar.jpg')
    # 替换目标图片
    shutil.copy2(source, target)
    print(f"[{datetime.now()}] 头像更新为: {chosen}")
# 调用示例
rotate_avatars(
    avatar_dir='D:\\workspace\\avatars',  # 头像库目录
    target_dir='C:\\Users\\Public\\pictures'  # 目标目录
)

Telegram机器人定时换头像

from telegram.ext import Updater, CommandHandler
import os
import glob
import random
class AvatarBot:
    def __init__(self, token):
        self.updater = Updater(token, use_context=True)
        self.dp = self.updater.dispatcher
        self.dp.add_handler(CommandHandler('change_avatar', self.change_avatar))
    def change_avatar(self, update, context):
        chat_id = update.effective_chat.id
        # 检查消息回复的图片
        if update.message.photo:
            file_id = update.message.photo[-1].file_id
            new_file = context.bot.get_file(file_id)
            new_file.download('new_avatar.jpg')
            # 调用Telegram Bot API设置头像
            context.bot.set_chat_photo(chat_id=chat_id, photo=open('new_avatar.jpg', 'rb'))
            update.message.reply_text('头像已更新!')
        else:
            # 从本地随机选择
            avatars = glob.glob('avatars/*.jpg')
            if avatars:
                chosen = random.choice(avatars)
                context.bot.set_chat_photo(chat_id=chat_id, photo=open(chosen, 'rb'))
                update.message.reply_text(f'头像已更换为: {os.path.basename(chosen)}')
            else:
                update.message.reply_text('没有可用的头像文件')

注意事项

平台 注意事项
微信/QQ 官方API限制严格,建议用辅助软件或手动操作
社交平台 频率限制(通常1小时/次),需设置随机延迟
GitHub 无官方API直接改头像,需模拟点击或桌面客户端
公司系统 建议先获得管理员授权再自动化

浏览器扩展方案(如需要)

// 油猴脚本示例 - 每天定时换头像
(function() {
    const avatars = [
        'https://example.com/avatar1.jpg',
        'https://example.com/avatar2.jpg',
        'https://example.com/avatar3.jpg'
    ];
    setInterval(() => {
        const randomAvatar = avatars[Math.floor(Math.random() * avatars.length)];
        const avatarImg = document.querySelector('.user-avatar');
        if (avatarImg) {
            avatarImg.src = randomAvatar;
            console.log('头像已更换:', new Date().toLocaleTimeString());
        }
    }, 3600000); // 每小时更换
})();

选择适合你的平台和应用场景的方案即可,自动化操作时注意遵守平台的服务条款,避免被封号。

抱歉,评论功能暂时关闭!