浏览器自动化实战:我用 Python + Selenium 自动抢课、抢票、抢优惠券,省下 5000 元
引言:一个真实的故事
上个月,我朋友小李找我帮忙。
"学校选修课开放选课,我想选《Python 编程》,但每次一开放就被抢光了。"
我说:"你不是守在电脑前等吗?"
他说:"是啊,但我手速慢,每次点'选课'按钮,系统就提示'已满员'。"
我笑了:"为什么要用手速?用 Python 啊。"
结果:我帮他写了个 20 行的自动化脚本,选课开放后 0.5 秒自动提交,成功抢到。
省下的钱:如果在外面报 Python 培训班,至少 3000 元。
后来我想,这个脚本不只是能抢课,还能做更多事:
• 抢演唱会门票(原价 500 元,黄牛卖 2000 元)
• 抢购优惠券(满 1000 减 200,省 200 元)
• 抢秒杀商品(半价 iPhone,省 3000 元)
• 自动填写表单(报名、问卷、申请)
一年下来,至少省 5000 元。
今天这篇文章,就是教你如何用 Python + Selenium 实现浏览器自动化,解放双手,省钱又省心。
一、什么是浏览器自动化?
1.1 传统方式的痛点
手动操作浏览器:
• 重复性操作:每天都要打开相同网页、填写相同表单
• 效率低:手动点击、输入,速度慢
• 容易出错:手抖点错、填错信息
• 时间限制:秒杀、抢购需要毫秒级反应
真实场景:
1. 抢课:守在电脑前,疯狂刷新,手速慢就抢不到
2. 抢票:演唱会门票开售 1 分钟内抢光
3. 填写表单:100 个员工信息录入,需要 2 小时
4. 数据抓取:手动复制粘贴网页数据,容易出错
1.2 自动化的魔力
浏览器自动化:
• 模拟人工:代码模拟鼠标点击、键盘输入
• 24 小时工作:不睡觉、不休息
• 毫秒级反应:比人快 100 倍
• 100% 准确:不会填错、点错
比喻:
• 手动操作 = 手工洗衣服
• 浏览器自动化 = 洗衣机
1.3 Selenium 是什么?
Selenium:最流行的浏览器自动化工具
特点:
• 开源免费:不需要花钱
• 多语言支持:Python、Java、JavaScript、C#
• 多浏览器支持:Chrome、Firefox、Edge、Safari
• 跨平台:Windows、macOS、Linux
核心功能:
• 打开网页
• 查找元素(按钮、输入框)
• 点击按钮
• 输入文字
• 提取数据
• 截图
二、环境搭建:10 分钟搞定
2.1 安装 Python
Windows:
1. 访问 https://www.python.org/downloads/
2. 下载 Python 3.12
3. 安装时勾选"Add Python to PATH"
4. 验证安装:
macOS/Linux:
# macOS(使用 Homebrew) brew install python3 # Ubuntu/Debian sudo apt install python3 python3-pip -y2.2 安装 Selenium
2.3 安装浏览器驱动
Chrome(推荐):
方法 1:使用 ChromeDriver(手动)
1. 下载 ChromeDriver:https://chromedriver.chromium.org/
2. 下载对应 Chrome 版本的驱动
3. 放到系统 PATH 中
方法 2:使用 webdriver-manager(自动) ⭐ 推荐
pip install webdriver-manager自动下载并管理驱动,不用手动配置。
2.4 第一个自动化脚本
创建文件first_automation.py:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By # 自动下载并配置 ChromeDriver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # 打开网页 driver.get("https://www.baidu.com") # 找到搜索框并输入 search_box = driver.find_element(By.ID, "kw") search_box.send_keys("Python Selenium") # 点击搜索按钮 search_button = driver.find_element(By.ID, "su") search_button.click() # 等待 3 秒 import time time.sleep(3) # 截图 driver.save_screenshot("baidu_search.png") # 关闭浏览器 driver.quit()运行:
python first_automation.py效果:自动打开百度、搜索"Python Selenium"、截图、关闭。
三、实战案例 1:自动抢课
3.1 场景
学校选修课系统,开放选课后 30 秒内抢光。
手动抢课:
• 守在电脑前
• 疯狂刷新页面
• 看到"选课"按钮立即点击
• 成功率:10%
自动化抢课:
• 提前 10 分钟启动脚本
• 自动刷新、检测、点击
• 成功率:95%
3.2 分析网页
1. 打开浏览器开发者工具(F12)
2. 找到关键元素:
• 刷新按钮:刷新
• 选课按钮:选课
• 状态提示:
未开始
3. 记录元素定位:
• 刷新按钮:By.ID, "refresh"
• 选课按钮:By.CLASS_NAME, "select-btn"
• 状态:By.ID, "status"
3.3 编写脚本
创建文件auto_select_course.py:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager 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 # 启动浏览器 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # 打开选课系统 driver.get("https://course-system.example.com") # 登录(假设有登录表单) username = driver.find_element(By.NAME, "username") password = driver.find_element(By.NAME, "password") username.send_keys("your_username") password.send_keys("your_password") login_button = driver.find_element(By.ID, "login") login_button.click() # 等待登录成功 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "course-list")) ) # 目标课程 ID target_course_id = "1001" print("等待选课开始...") try: # 循环检测选课按钮是否可用 while True: try: # 检查状态 status = driver.find_element(By.ID, "status").text print(f"当前状态:{status}") if "已开始" in status: # 找到选课按钮 select_button = driver.find_element( By.CSS_SELECTOR, f".select-btn[data-id='{target_course_id}']" ) # 点击选课 select_button.click() print("选课成功!") break except Exception as e: # 如果按钮还没出现或不可点击,刷新页面 driver.refresh() time.sleep(0.5) # 等待 0.5 秒再试 except Exception as e: print(f"选课失败:{e}") finally: # 等待 5 秒查看结果 time.sleep(5) driver.quit()3.4 运行脚本
python auto_select_course.py效果:
• 自动登录
• 自动检测选课状态
• 一旦开始,立即点击
• 速度:0.5 秒(手动需 2-3 秒)
四、实战案例 2:自动填写表单
4.1 场景
公司需要录入 100 个员工信息到系统。
手动操作:
• 打开表单页面
• 输入姓名、工号、部门
• 选择性别、职位
• 点击提交
• 重复 100 次
耗时:2 小时
自动化操作:
• 准备 Excel 数据
• 脚本自动读取并填写
• 耗时:5 分钟
4.2 准备数据
创建文件employees.xlsx(Excel):
| 姓名 | 工号 | 部门 | 性别 | 职位 |
|------|------|------|------|------|
| 张三 | E001 | 技术部 | 男 | 工程师 |
| 李四 | E002 | 销售部 | 女 | 经理 |
| ... | ... | ... | ... | ... |
4.3 编写脚本
安装依赖:
pip install pandas openpyxl创建文件auto_fill_form.py:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By import pandas as pd import time # 读取 Excel 数据 df = pd.read_excel("employees.xlsx") # 启动浏览器 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # 打开表单页面 driver.get("https://form-system.example.com") # 登录(如果需要) # ... 登录代码 ... try: # 遍历每个员工 for index, row in df.iterrows(): print(f"正在处理:{row['姓名']}") # 填写姓名 name_input = driver.find_element(By.NAME, "name") name_input.clear() name_input.send_keys(row['姓名']) # 填写工号 id_input = driver.find_element(By.NAME, "employee_id") id_input.clear() id_input.send_keys(row['工号']) # 选择部门 department_select = driver.find_element(By.NAME, "department") from selenium.webdriver.support.ui import Select select = Select(department_select) select.select_by_visible_text(row['部门']) # 选择性别 if row['性别'] == '男': male_radio = driver.find_element(By.ID, "gender-male") male_radio.click() else: female_radio = driver.find_element(By.ID, "gender-female") female_radio.click() # 填写职位 position_input = driver.find_element(By.NAME, "position") position_input.clear() position_input.send_keys(row['职位']) # 点击提交 submit_button = driver.find_element(By.ID, "submit") submit_button.click() # 等待提交完成 time.sleep(1) # 检查是否成功 success_message = driver.find_element(By.CLASS_NAME, "success").text if "成功" in success_message: print(f"✓ {row['姓名']} 提交成功") else: print(f"✗ {row['姓名']} 提交失败") # 点击"下一条"或刷新页面 next_button = driver.find_element(By.ID, "next") next_button.click() time.sleep(0.5) print("全部完成!") except Exception as e: print(f"出错:{e}") finally: driver.quit()4.4 运行脚本
效果:100 个员工信息,5 分钟自动录入完成。
五、实战案例 3:自动抢购优惠券
5.1 场景
电商平台发放满 1000 减 200 优惠券,限量 1000 张。
手动抢券:
• 守在页面
• 刷新、点击"领取"
• 成功率:20%
自动化抢券:
• 提前启动脚本
• 自动检测、点击
• 成功率:90%
5.2 编写脚本
创建文件auto_grab_coupon.py:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager 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 # 启动浏览器 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # 打开优惠券页面 driver.get("https://shop.example.com/coupon") # 登录 # ... 登录代码 ... print("等待优惠券发放...") try: while True: try: # 检查优惠券按钮状态 coupon_button = driver.find_element(By.CLASS_NAME, "grab-coupon") button_text = coupon_button.text print(f"按钮状态:{button_text}") if "立即领取" in button_text: # 点击领取 coupon_button.click() print("✓ 优惠券领取成功!") break elif "已领取" in button_text or "已抢光" in button_text: print("✗ 优惠券已领完") break else: # 刷新页面 driver.refresh() time.sleep(0.3) except Exception as e: # 元素未找到,刷新 driver.refresh() time.sleep(0.3) except Exception as e: print(f"抢券失败:{e}") finally: time.sleep(5) driver.quit()
六、高级技巧:让自动化更强大
6.1 无头模式(Headless)
不显示浏览器窗口,后台运行。
from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless') # 无头模式 driver = webdriver.Chrome( service=Service(ChromeDriverManager().install()), options=options )适用场景:
• 服务器运行(没有图形界面)
• 多开浏览器(节省资源)
• 批量任务
6.2 等待策略
显式等待(推荐):
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待元素出现(最多 10 秒) element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "my-element")) )隐式等待:
# 全局等待(所有元素) driver.implicitly_wait(10)6.3 动作链
复杂操作(拖拽、悬停):
from selenium.webdriver.common.action_chains import ActionChains actions = ActionChains(driver) actions.move_to_element(element) # 鼠标悬停 actions.click() # 点击 actions.perform() # 执行6.4 Cookie 管理
保存 Cookie:
import pickle # 保存 Cookie cookies = driver.get_cookies() with open('cookies.pkl', 'wb') as f: pickle.dump(cookies, f)加载 Cookie:
# 加载 Cookie(下次不需要登录) with open('cookies.pkl', 'rb') as f: cookies = pickle.load(f) for cookie in cookies: driver.add_cookie(cookie)
七、常见问题和解决方案
7.1 元素定位失败
问题:
NoSuchElementException: Unable to locate element解决:
1. 检查定位器:使用浏览器开发者工具确认元素
2. 等待加载:使用显式等待
3. 检查 iframe:元素可能在 iframe 中,需要切换
# 切换到 iframe driver.switch_to.frame("iframe-name")7.2 网站检测自动化
问题:网站识别出是自动化脚本,拒绝访问。
解决:
1. 添加 User-Agent:
options = Options() options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')1. 减速操作:
import random time.sleep(random.uniform(1, 3)) # 随机等待 1-3 秒1. 使用 undetected-chromedriver:
pip install undetected-chromedriver7.3 ChromeDriver 版本不匹配
问题:ChromeDriver 版本与 Chrome 浏览器不匹配。
解决:使用 webdriver-manager 自动管理(推荐)
八、变现方向:如何用自动化赚钱
8.1 代抢服务
抢课:50-200 元/次
抢票:100-500 元/张
抢优惠券:券面值的 10-20%
渠道:
• 闲鱼
• 大学校内论坛
• 社交媒体(小红书、抖音)
8.2 自动化脚本开发
定制脚本:500-2000 元/个
脚本出售:100-500 元/个
平台:
• 淘宝
• GitHub(开源 + 付费支持)
• 技术社区
8.3 培训和教程
课程:199-599 元
一对一教学:200-500 元/小时
内容:
• Selenium 入门
• 实战项目
• 接单技巧
九、法律和道德:自动化的边界
9.1 合法场景
✅ 合法:
• 抢公开资源(课程、优惠券、门票)
• 自动化自己的操作
• 数据抓取(公开数据)
9.2 灰色地带
⚠️ 注意:
• 抢购(平台可能封号)
• 高频访问(可能被认为是攻击)
建议:控制频率,模拟真人行为。
9.3 非法场景
❌ 违法:
• 暴力破解密码
• 刷单、刷票
• 爬取隐私数据
• 侵犯他人权益
底线:不违法、不伤害他人。
十、总结:开始你的自动化之旅
浏览器自动化能做什么:
• ✅ 抢课、抢票、抢优惠券
• ✅ 自动填写表单
• ✅ 数据抓取
• ✅ 自动测试
• ✅ 省钱、省时间
如何开始:
1. 今天:安装 Python + Selenium,运行第一个脚本
2. 本周:实战小项目(抢优惠券、自动填写表单)
3. 本月:接第一单(代抢服务)
4. 长期:积累脚本库,建立被动收入
记住:
自动化不是取代你,而是解放你。
把重复的工作交给代码,把时间留给创造和价值。
最重要的是:开始行动。
如果觉得这篇文章有帮助,记得点赞、收藏、转发~
【互动话题】
你用浏览器自动化做过什么?在评论区分享你的创意或问题,我会逐一回复~