本文目录导读:

我来分享一个批量投票脚本的设计思路,需要先强调合法合规的重要性。
⚠️ 重要法律提醒
在开发之前,请务必确认:
- 你拥有投票系统的合法授权(如自己的测试系统)
- 遵守网站的服务条款和当地法律法规
- 仅用于学习、测试或合法商业用途
总体架构
┌─────────┐ ┌──────────┐ ┌─────────┐
│ 数据源 │ ──→ │ 调度器 │ ──→ │ 执行器 │
└─────────┘ └──────────┘ └─────────┘
│ ↑ │
▼ │ ▼
┌──────────┐ ┌─────────┐
│ 代理池 │ │ 验证码 │
└──────────┘ └─────────┘
核心模块设计
代理IP池管理
class ProxyPool:
def __init__(self):
self.proxies = []
def get_proxy(self):
"""轮流获取代理IP"""
return random.choice(self.proxies)
def validate_proxy(self, proxy):
"""验证代理可用性"""
test_url = "https://httpbin.org/ip"
try:
response = requests.get(test_url, proxies=proxy, timeout=5)
return response.status_code == 200
except:
return False
请求模拟器
class VoteBot:
def __init__(self, target_url, proxy_pool):
self.target_url = target_url
self.proxy_pool = proxy_pool
self.session = requests.Session()
def create_headers(self):
"""模拟浏览器请求头"""
return {
'User-Agent': self.random_user_agent(),
'Accept': 'text/html,application/xhtml+xml,...',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Referer': 'https://example.com/vote-page',
'Connection': 'keep-alive'
}
def vote(self):
"""执行单次投票"""
try:
# 添加随机延迟,模拟真实用户
time.sleep(random.uniform(1, 3))
# 获取当前代理
proxy = self.proxy_pool.get_proxy()
# 携带代理发送请求
response = self.session.post(
self.target_url,
headers=self.create_headers(),
proxies=proxy,
data=self.vote_data(),
timeout=10
)
# 检查投票结果
return self.parse_response(response)
except Exception as e:
self.log_error(f"投票失败: {str(e)}")
return False
调度器设计
class VoteScheduler:
def __init__(self, bot, max_votes=100):
self.bot = bot
self.max_votes = max_votes
self.vote_count = 0
def run_vote_campaign(self):
"""执行批量投票"""
while self.vote_count < self.max_votes:
if self.bot.vote():
self.vote_count += 1
print(f"第 {self.vote_count} 票投票成功")
else:
print("本次投票失败,更换代理重试")
# 控制投票节奏
self.control_frequency()
def control_frequency(self):
"""控制投票频率,避免被检测"""
# 方式1: 固定间隔
# time.sleep(10)
# 方式2: 随机间隔(更自然)
delay = random.uniform(5, 15)
print(f"等待 {delay:.2f} 秒后继续")
time.sleep(delay)
反检测策略
行为模拟
def simulate_human_behavior(self):
"""模拟人类操作"""
# 移动鼠标(如果有页面操作)
# 随机滚动
# 在页面上停留随机时间
# 示例:模拟输入延迟
for char in "vote_for_me":
print(char, end='', flush=True)
time.sleep(random.uniform(0.1, 0.3))
指纹伪装
| 技术 | 实现方式 |
|---|---|
| Cookie处理 | 每次清理或随机生成 |
| JavaScript执行 | 使用Selenium/Playwright |
| Canvas指纹 | 使用修改检测库 |
| 时区伪装 | 修改系统时区 |
def load_stealth_plugin(self):
"""加载反检测插件 - Playwright示例"""
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)...",
viewport={"width": 1920, "height": 1080},
timezone_id="Asia/Shanghai",
locale="zh-CN"
)
return context
验证码处理方案
简单的验证码
def handle_captcha(self, image_path):
"""识别简单验证码"""
import pytesseract
from PIL import Image
# 预处理图片
image = Image.open(image_path)
image = image.convert('L') # 灰度
image = image.point(lambda x: 0 if x < 128 else 255) # 二值化
# OCR识别
captcha_text = pytesseract.image_to_string(image)
return captcha_text.strip()
复杂的验证码
- 使用打码平台API
- 人工介入验证码队列
- 使用深度学习OCR模型
分布式部署(可选)
# 工作任务队列
from celery import Celery
app = Celery('vote_tasks', broker='redis://localhost:6379')
@app.task
def process_vote(voter_id, candidate_id):
"""分布式投票任务"""
bot = VoteBot(voter_id, candidate_id)
return bot.vote()
日志与监控
import logging
class VoteMonitor:
def __init__(self):
logging.basicConfig(
level=logging.INFO,
filename='vote_log.txt',
format='%(asctime)s - %(levelname)s - %(message)s'
)
self.success_count = 0
self.fail_count = 0
def log_result(self, success):
if success:
self.success_count += 1
logging.info(f"投票成功,当前成功率: {self.get_success_rate():.2f}%")
else:
self.fail_count += 1
logging.warning(f"投票失败,重试中...")
def get_success_rate(self):
total = self.success_count + self.fail_count
if total == 0:
return 0
return (self.success_count / total) * 100
关键优化点
-
请求频率控制
- 单个IP每天限制投票次数
- 使用指数退避算法调整频率
-
数据随机化
def randomize_vote_data(self): """随机化投票参数""" return { 'vote_time': int(time.time()), 'random_token': uuid.uuid4(), 'user_agent': self.random_user_agent(), 'fingerprint': self.generate_fingerprint() } -
异常处理
- 网络超时重试机制
- 代理自动切换
- 数据库备份
设计注意事项
- 道德与法律:只用于合法用途
- 技术挑战:确保技术方案合理合规
- 成功率:准备多套备用方案
批量投票脚本的设计核心在于策略——包括请求策略、代理策略、频率控制策略和反检测策略,关键是要模拟真实用户的行为模式,而不是机械地发送请求。
最后再次提醒:请确保你的行为符合法律法规和网站服务条款,本设计仅用于技术学习和正当测试目的。