本文目录导读:

我来介绍几种编写自动化签到脚本的方法,从简单到复杂:
Python + Requests 方式(最常用)
基础示例
import requests
import json
import time
class AutoSign:
def __init__(self, username, password):
self.username = username
self.password = password
self.session = requests.Session()
def login(self):
"""登录获取cookie/token"""
login_url = "https://example.com/api/login"
data = {
"username": self.username,
"password": self.password
}
response = self.session.post(login_url, json=data)
if response.status_code == 200:
return True
return False
def sign(self):
"""执行签到"""
sign_url = "https://example.com/api/sign"
try:
response = self.session.post(sign_url)
return response.json()
except Exception as e:
print(f"签到失败: {e}")
return None
def run(self):
"""主运行函数"""
if self.login():
result = self.sign()
if result:
print(f"签到成功: {result}")
else:
print("登录失败")
使用 Selenium(模拟浏览器)
适用于需要JavaScript渲染的网站:
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
class SeleniumAutoSign:
def __init__(self):
# 使用Chrome无头模式
options = webdriver.ChromeOptions()
options.add_argument('--headless') # 无头模式
options.add_argument('--no-sandbox')
self.driver = webdriver.Chrome(options=options)
def auto_sign(self):
try:
# 打开签到页面
self.driver.get("https://example.com/sign")
# 等待元素加载
wait = WebDriverWait(self.driver, 10)
sign_btn = wait.until(
EC.element_to_be_clickable((By.ID, "sign-btn"))
)
# 点击签到按钮
sign_btn.click()
# 等待结果
time.sleep(2)
result = self.driver.find_element(By.CLASS_NAME, "result").text
print(f"签到结果: {result}")
finally:
self.driver.quit()
完整项目结构
创建一个完善的签到项目:
# config.py - 配置文件
import json
class Config:
@staticmethod
def load_config():
with open('config.json', 'r') as f:
return json.load(f)
# sign_task.py - 主程序
import logging
import datetime
from config import Config
def setup_logging():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('sign.log'),
logging.StreamHandler()
]
)
def main():
setup_logging()
config = Config.load_config()
# 创建签到对象
signer = AutoSign(
config['username'],
config['password']
)
# 执行签到
try:
result = signer.run()
if result:
logging.info(f"签到成功: {datetime.datetime.now()}")
else:
logging.warning(f"签到失败: {datetime.datetime.now()}")
except Exception as e:
logging.error(f"程序异常: {e}")
if __name__ == "__main__":
main()
配置文件示例
{
"username": "your_username",
"password": "your_password",
"sign_url": "https://example.com/sign",
"login_url": "https://example.com/login",
"retry_times": 3,
"notify": {
"email": "your_email@example.com",
"wechat": "your_wechat_token"
}
}
定时任务设置
Windows 任务计划程序
:: 创建批处理文件 run_sign.bat @echo off cd /d D:\auto_sign python sign_task.py
Linux Crontab
# 每天8点执行 0 8 * * * cd /path/to/your/script && python3 sign_task.py >> sign.log 2>&1
Python schedule
import schedule
import time
def job():
signer = AutoSign("username", "password")
signer.run()
# 每天早上8点执行
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
异常处理和通知
import smtplib
from email.mime.text import MIMEText
def send_notification(message):
"""发送邮件通知"""
msg = MIMEText(message)
msg['Subject'] = '签到结果通知'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
# 发送邮件
server = smtplib.SMTP('smtp.example.com', 587)
server.login('your_email', 'your_password')
server.send_message(msg)
server.quit()
class SignWithRetry:
def __init__(self, max_retries=3):
self.max_retries = max_retries
def sign_with_retry(self, sign_function):
for attempt in range(self.max_retries):
try:
result = sign_function()
if result:
return result
time.sleep(5) # 等待5秒重试
except Exception as e:
logging.error(f"第{attempt+1}次尝试失败: {e}")
send_notification("签到多次尝试失败!")
return None
注意事项
- 遵守规则:不要对目标网站造成压力,合理设置请求频率
- 隐私保护:不要在代码中硬编码密码,使用环境变量或配置文件
- 错误处理:做好异常处理和日志记录
- 合法性:确认签到行为不违反网站服务条款
- 定期维护:网站可能更新页面结构,需要及时更新脚本
调试技巧
import config
import logging
# 开启调试模式
logging.basicConfig(level=logging.DEBUG)
# 使用代理
proxies = {
'http': 'http://proxy.example.com:8080',
'https': 'https://proxy.example.com:8080'
}
# 添加请求头模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json, text/plain, */*',
'Origin': 'https://example.com'
}
这些方法可以根据实际场景组合使用,选择合适的方案来构建你的自动化签到脚本,建议先在测试环境调试,确认无误后再部署到生产环境。