T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 48 天:Selenium:让浏览器自己玩游戏

这是「Python 100 天」系列第 48 天的学习笔记:Selenium:让浏览器自己玩游戏。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

用 Selenium 打开"Cookie Clicker"网页游戏,反复点击大饼干攒点数,每隔 5 秒买最贵的买得起的建筑,形成自动挂机。README 知识点:用 Selenium 定位元素、抓取数据、自动填表单和点按钮。

一、Selenium 与 requests 的区别

requests + BeautifulSoup Selenium
执行 JS不会会
能点击/输入不能能
速度快慢
适用静态页面、接口动态页面、需要交互

页面内容由 JavaScript 渲染时,requests 拿到的是空壳,必须用 Selenium 驱动真实浏览器。

二、启动浏览器

1
2
3
4
5
6
7
8
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service("C:\Development\chromedriver.exe") # 驱动路径
driver = webdriver.Chrome(service=service)
driver.get("https://example.com")
driver.quit() # 别忘了关

Selenium 4.6+ 之后通常不需要手动下载驱动,webdriver.Chrome() 会自动匹配版本。老教程里的路径写法在 macOS 上也不适用(应该是 /usr/local/bin/chromedriver)。

三、定位元素

1
2
3
driver.find_element(By.ID, "cookie")                       # 单个,找不到抛异常
driver.find_elements(By.CSS_SELECTOR, "#store .grayed b") # 多个,找不到返回 []
driver.find_element(By.XPATH, '//*[@id="money"]')

find_element 找不到会抛 NoSuchElementException,find_elements 返回空列表——这个差别决定了你写不写 try。

常用交互:

1
2
3
4
element.click()
element.send_keys("文本") # 输入
element.text # 取文本
element.get_attribute("href")

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time

service = Service("C:Developmentchromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("http://orteil.dashnet.org/experiments/cookie/")

cookie = driver.find_element(by=By.ID, value="cookie")
store = driver.find_elements(by=By.CSS_SELECTOR, value="#store .grayed b")
price_list = [int(price.text.split('-')[1].strip().replace(",", "")) for price in store if price.text]

store_dict = {
0: "Cursor",
1: "Grandma",
2: "Factory",
3: "Mine",
4: "Shipment",
5: "Alchemy lab",
6: "Portal",
7: "Time machine",
}


def cookie_clicker():
check = time.time() + 5
while True:
cookie.click()
if time.time() > check:
purchase()
break


def purchase():
my_points = driver.find_element(by=By.XPATH, value='//*[@id="money"]')
my_points = int(my_points.text.replace(",", ""))
purchase_item = store_dict[price_list.index([item for item in price_list if my_points > item][-1])]
driver.find_element(by=By.CSS_SELECTOR, value=f"#store #buy{purchase_item}").click()
cookie_clicker()


cookie_clicker()

代码走读

  1. Service(...) 指定驱动,webdriver.Chrome 启动浏览器,get 打开游戏页。
  2. cookie = driver.find_element(By.ID, "cookie"):大饼干按钮。
  3. store = driver.find_elements(By.CSS_SELECTOR, "#store .grayed b"):只取"买不起"(灰色)的建筑价格,b 标签里是 "Cursor - 15" 这样的文本。
  4. price_list:切出价格、去逗号、转 int。
  5. store_dict:把建筑下标映射成名字,用于拼 #buyCursor 这样的 id。
  6. cookie_clicker():死循环点 5 秒 → 调 purchase() → 再递归回自己。
  7. purchase():读当前点数 → 在"买得起的价格"里取最大的 → 点对应的购买按钮 → 回到点击循环。

这段代码的关键逻辑

1
purchase_item = store_dict[price_list.index([item for item in price_list if my_points > item][-1])]

从里往外读:

  1. [item for item in price_list if my_points > item]:所有买得起的价格;
  2. [-1]:其中最大的(price_list 是从便宜到贵排序的);
  3. .index(...):这个价格在原始列表里的下标;
  4. store_dict[下标] → 建筑名字。

一行代码干了四件事,可读性极差。拆成三行会清楚得多。

这份代码的问题

  • price_list 只抓了一次(页面刚打开时全是灰色),随着购买,建筑会从灰变亮,列表就不准了。要每次购买前重新抓。
  • 递归代替循环:purchase 调 cookie_clicker,cookie_clicker 又调 purchase,跑久了栈会溢出。应该用一个 while True 加状态。
  • store 为空时 price_list.index(...) 抛 ValueError。
  • 没有 driver.quit():浏览器进程会一直留着。

运行效果

浏览器自动打开游戏页,饼干数飞涨,每 5 秒买一个建筑。

易错点

  1. 驱动版本与浏览器不匹配:SessionNotCreatedException。
  2. 元素还没加载就查找:需要 WebDriverWait(driver, 10).until(EC.presence_of_element_located(...)),不要用 time.sleep 硬等。
  3. find_element 抛异常:想"找不到就跳过"必须用 find_elements。
  4. 窗口被手动关闭:驱动报 WebDriverException。

动手改

  • 用 while True 重写,去掉递归。
  • 每次购买前重新抓价格列表。
  • 加 try/finally 保证 driver.quit() 一定执行。

源文件逐个讲解

2 个文件:

文件 行数 职责
main.py45自动点饼干 → 每 5 秒买最贵的能买的升级
README.md9说明页

main.py(45 行)——全书第一个 Selenium 脚本

(1)三行启动 Chrome

1
2
3
4
5
6
7
8
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time

service = Service("C:Developmentchromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("http://orteil.dashnet.org/experiments/cookie/")

Service("C:Developmentchromedriver.exe") 是 Windows 路径——在 macOS/Linux 上必须换成 /usr/local/bin/chromedriver 之类,否则 WebDriverException。

这个字符串里 D、c 是无效转义:Python 会警告 DeprecationWarning: invalid escape sequence D,但因为 D 不是合法转义,实际保留成字面 D,所以恰好还能用。规范写法是 r"C:Developmentchromedriver.exe"(原始字符串)或用 /。

Service 对象是 Selenium 4 的新写法;Day 50/52 用的 webdriver.Chrome(executable_path=...) 是 Selenium 3 的旧写法(Selenium 4.6+ 已废弃,会报错)。同一个课程里两种写法并存,说明作者是在 Selenium 升级期间写的。

(2)By.ID 与 By.CSS_SELECTOR

1
2
cookie = driver.find_element(by=By.ID, value="cookie")
store = driver.find_elements(by=By.CSS_SELECTOR, value="#store .grayed b")

find_element 返回第一个匹配(找不到抛 NoSuchElementException); find_elements 返回列表(找不到返回 [],不抛异常)——这个区别非常重要。

#store .grayed b:CSS 选择器——#store 里 class 为 grayed 的元素下的 <b> 标签。

.grayed 是关键:DashNet 的饼干店会给「买不起」的升级加 grayed 类。所以这一行抓到的全是「当前买不起的」——这个逻辑很绕,见下面 purchase()。

(3)价格列表推导

1
price_list = [int(price.text.split('-')[1].strip().replace(",", "")) for price in store if price.text]

拆开看:

  • price.text 形如 "Cursor - 15";
  • .split('-')[1] 取 " 15";
  • .strip() 去掉空格;
  • .replace(",", "") 去掉千分位逗号("1,000" → "1000");
  • int(...) 转数字;
  • if price.text 过滤空文本(有些 <b> 是空的)。

四个字符串操作串起来——这就是「数据清洗」在爬虫里的日常。

(4)硬编码的升级表

1
2
3
4
store_dict = {
0: "Cursor", 1: "Grandma", 2: "Factory", 3: "Mine",
4: "Shipment", 5: "Alchemy lab", 6: "Portal", 7: "Time machine",
}

下标 → 升级名的映射,顺序必须和网页上 <b> 的顺序一致。一旦游戏更新加了新升级,这个字典就错了。

更好的写法:直接从页面抓 #buyCursor 这类 id,不用手工维护。

(5)主循环

1
2
3
4
5
6
7
8
9
10
11
12
def cookie_clicker():
check = time.time() + 5
while True:
cookie.click()
if time.time() > check:
purchase()
break


def purchase():
...
cookie_clicker()

cookie_clicker 和 purchase 互相调用——这是递归:

1
cookie_clicker → 点 5 秒 → purchase → 买东西 → cookie_clicker → ...

为什么用递归而不是 while True? 因为要在「中间插入买东西」。但递归会不断加深调用栈——跑几小时可能 RecursionError(Python 默认 1000 层)。while + 状态变量更安全。

check = time.time() + 5:从现在起 5 秒后到期。每次调用 purchase 都会重新计时。

(6)purchase() 的核心一行

1
2
3
4
5
6
def purchase():
my_points = driver.find_element(by=By.XPATH, value='//*[@id="money"]')
my_points = int(my_points.text.replace(",", ""))
purchase_item = store_dict[price_list.index([item for item in price_list if my_points > item][-1])]
driver.find_element(by=By.CSS_SELECTOR, value=f"#store #buy{purchase_item}").click()
cookie_clicker()

purchase_item 这一行嵌套了四层,拆开看:

1
2
3
4
affordable = [item for item in price_list if my_points > item]  # 买得起的
most_expensive = affordable[-1] # 最贵的那个
index = price_list.index(most_expensive) # 它在原列表的下标
name = store_dict[index] # 名字

逻辑是「买最贵的能买的」——这是游戏里的最优策略。

但这里有个隐藏假设:price_list 必须是升序的(Cursor 最便宜、Time machine 最贵),[-1] 才是「最贵的」。如果网页顺序变了,就买错。

price_list.index(...) 也有坑:如果两个升级同价(游戏里确实会出现),index 返回第一个,可能买错。

f"#store #buy{purchase_item}":拼出 #store #buyCursor 这样的 id。升级名里带空格("Alchemy lab")→ #buyAlchemy lab,CSS 选择器会解析失败。这是一个真 bug:买到「炼金实验室」那一步就崩。

这份代码的问题

  1. #buyAlchemy lab 带空格,选择器非法(真 bug)。
  2. price_list 假设升序,同价时 index 取错。
  3. store_dict 硬编码 8 项,游戏更新就失效。
  4. 递归调用,长时间运行会爆栈。
  5. Windows 路径 + 无效转义。
  6. 没有 driver.quit(),进程会残留。
  7. price_list 是「买不起」的价格——这个语义作者自己也没写注释,命名误导。

README.md(9 行)

标题 Day 48 - Selenium Webdriver Browser and Game Playing Bot,知识点:Selenium Webdriver、Installing & Setting up Selenium、How to Find and Select Elements、Interacting with Webpages。

四条:Webdriver、安装配置、元素定位、页面交互。这一天最重要的是「让代码操作浏览器」这个范式——之后的 49~52 全是它的变体。

微信收款码 微信
支付宝收款码 支付宝
评论