Code2025

异步浏览器自动化:Playwright 并发抓 5 页,为什么不是快 5 倍

写于 2026-11-15·更新于 2026-11-15·7385 字·4 段可运行·1 条反链
本页目录

问题从哪来#

示例 8 是本单元唯一的完整项目,作业题目是「使用 Playwright 异步批量采集当当图书网中书籍的信息」。它的核心就两段:

python
async def get_book_data(page_num):    async with async_playwright() as playwright:        browser = await playwright.chromium.launch()          # ← 每页开一个浏览器        page = await browser.new_page()        await page.goto(f'http://bang.dangdang.com/books/bestsellers/...-1-{page_num}')        html = await page.content()        html_tree = etree.HTML(html)                          # ← 拿回字符串用 lxml 解析        for book_info in html_tree.xpath('//ul[@class="bang_list clearfix bang_list_mode"]/li'):            book_title = book_info.xpath('./div[@class="name"]/a/@title')[0]            book_price = book_info.xpath('./div[@class="price"]/p[1]/span[1]/text()')[0]            print(book_title, book_price) async def main(number):    task_list = []    for i in range(1, number + 1):        task = asyncio.create_task(get_book_data(i))          # ← 创建即开始调度        task_list.append(task)    await asyncio.wait(task_list) if __name__ == '__main__':    page_number = int(input('请输入抓取的页数:'))    start_time = time.time()    asyncio.run(main(page_number))    print('程序运行时间为:', time.time() - start_time)

三个问题:

  1. 从「当当那份 Selenium 代码一页一页翻」变成「N 页同时抓」,凭什么快了?
  2. number 是 input() 进来的,用户敲 100 会怎样?
  3. 为什么不用多线程?多线程不也能同时干几件事吗?

第一步:create_task 到底做了什么#

asyncio.create_task(coro) 把协程对象包成 Task 并立刻注册进事件循环——注意是「立刻」,不用等 await。所以那个 for 循环跑完的瞬间,N 个任务已经在事件循环里排队等机会执行了。await asyncio.wait(task_list) 只是站在门口等它们全干完。

关键在于事件循环是单线程的。它不是真的同时跑 N 个任务,而是:

text
事件循环(一个线程,一个待办队列)

  任务1: launch ─┐await(让出)
  任务2: launch ─┼─await(让出)        ← for 循环极快地把 5 个都推到 await 点
  任务3: launch ─┤
  任务4: launch ─┤
  任务5: launch ─┘
                 ↓
  ┌──────────────────────────────────────┐
  │  5 个任务都在等各自的浏览器/网络      │  ← 这段时间 CPU 是空的
  │  谁的数据先回来,事件循环就先叫醒谁   │
  └──────────────────────────────────────┘
                 ↓
  任务3 先完成解析 → 任务1 → 任务5 → 任务2 → 任务4

await 是「我这里要等 IO,你先去忙别的」。协程的并发能力完全建立在这句话上:等待的时间被重叠起来了。

第二步:并发到底快多少(本机真跑)#

Playwright 本机装了,但浏览器内核没下载,绝对不能启动。不过「等待被重叠」这件事和网络无关,用 asyncio.sleep 模拟同样的等待结构就能量出来 —— await asyncio.sleep() 和 await page.goto() 在事件循环看来是完全一样的:都是让出控制权。

python
import asyncioimport time  async def fake_page_load(page_num, cost=0.30):    """模拟「打开浏览器 → 加载页面 → 拿 HTML」的等待。    await asyncio.sleep 会让出事件循环,这正是真实网络/渲染等待的行为特征。"""    await asyncio.sleep(cost)    return f"第{page_num}页 HTML"  async def demo_serial():    """写法一:串行 —— 每次 await 都等上一个彻底干完,等于没有并发"""    t0 = time.monotonic()    out = []    for i in range(1, 6):        out.append(await fake_page_load(i))    return time.monotonic() - t0, out  async def demo_gather():    """写法二:先全部 create_task,再一起等 —— 5 个任务的等待时间互相重叠"""    t0 = time.monotonic()    tasks = [asyncio.create_task(fake_page_load(i)) for i in range(1, 6)]    out = await asyncio.gather(*tasks)    return time.monotonic() - t0, list(out)  async def main():    c1, o1 = await demo_serial()    c2, o2 = await demo_gather()    print(f"串行 for + await : {c1:.2f}s   结果 {o1[:2]} ...")    print(f"gather 并发      : {c2:.2f}s   结果 {o2[:2]} ...")    print(f"加速比 {c1 / c2:.1f} 倍(5 个任务,理论上限就是 5 倍)")  asyncio.run(main())

5 个任务、每个 0.3 秒,串行 1.53 秒,并发 0.31 秒。加速比 4.9 倍,逼近理论上限 5 倍——因为模拟的等待是纯 IO、CPU 完全空闲。

第三步:真实场景为什么达不到 4.9 倍#

上面那个数字有欺骗性。换成真的浏览器,加速比会明显缩水,原因是三笔开销不会重叠:

看一项开销时,先问它是在等,还是正在做计算。

  • 可以重叠的是网络等待。 DNS、建连、服务器响应期间,其他任务可以向前推进。省下来的是重叠的等待时间。
  • 启动也要占用资源。 launch() 会创建进程,消耗 CPU 和内存。一次同时创建 20 个浏览器时,启动过程也会争抢这些资源。
  • 渲染与解析仍须完成。 网页渲染和 JavaScript 执行需要 CPU。etree.HTML(html) 与 XPath 解析也需要实际计算,同一个 Python 事件循环中的协程不会在这些同步调用中主动让出。

最后一行是最容易被忽略的:html_tree.xpath(...) 是 CPU 密集型操作,执行期间根本没有 await,事件循环动不了,其他任务全被卡住。所以「异步」只对 IO 密集有效,当当那份代码里的 lxml 解析部分,异步一点忙都帮不上。

第四步:并发必须设上限,否则输入 20 就开 20 个浏览器#

示例 8 的 number 来自 input(),没有任何上限检查。用户敲 5,开 5 个 Chrome 还能忍;敲 50,机器直接卡死。

用 asyncio.Semaphore 限流,并且顺手把「同一瞬间到底开了几个」量出来:

python
import asyncioimport time running = 0peak = 0  async def open_browser(i, cost=0.20):    """模拟示例8:每个任务各自 launch 一个浏览器。    全局计数器记录「此刻有几个在跑」,peak 记下整个过程的最大值 —— 这就是峰值并发。"""    global running, peak    running += 1    peak = max(peak, running)    await asyncio.sleep(cost)    running -= 1    return i  async def demo_peak(n, limit=None):    global running, peak    running, peak = 0, 0    sem = asyncio.Semaphore(limit) if limit else None     async def guarded(i):        if sem is None:            return await open_browser(i)        async with sem:                  # 信号量满了就在这里排队,不进去            return await open_browser(i)     t0 = time.monotonic()    await asyncio.gather(*(guarded(i) for i in range(1, n + 1)))    return time.monotonic() - t0, peak  async def main():    for n, lim in [(8, None), (8, 3), (20, None), (20, 3)]:        c, p = await demo_peak(n, lim)        tag = "无 Semaphore" if lim is None else f"Semaphore({lim})"        print(f"{n:2d} 页 {tag:14s} 耗时 {c:.2f}s  同一瞬间开着的浏览器数 = {p}")  asyncio.run(main())

看第三行:20 个任务,同一瞬间 20 个浏览器全开着。示例 8 现在的行为就是这样。

加上 Semaphore(3),峰值被死死压在 3,代价是耗时从 0.20s 涨到 1.44s(≈ ⌈20/3⌉ × 0.2s)。这个交换在真实场景里必须做 —— 因为真实的浏览器启动不是 0 秒。

第五步:asyncio.wait 和 asyncio.gather 不是一回事#

示例 8 用的是 await asyncio.wait(task_list),而且返回值直接被扔掉了。这两个 API 差别不小:

python
import asyncio  async def fake_page_load(page_num, cost=0.30):    await asyncio.sleep(cost)    return f"第{page_num}页 HTML"  async def main():    # asyncio.wait:返回 (done, pending) 两个「集合」    t1 = asyncio.create_task(fake_page_load(1, 0.3))    t2 = asyncio.create_task(fake_page_load(2, 0.1))    done, pending = await asyncio.wait([t1, t2])    print("asyncio.wait 返回:", type(done).__name__, len(done), "个 / pending", len(pending), "个")    print("  从 done 里取结果(集合无序):", sorted(t.result() for t in done))     # asyncio.gather:直接返回结果「列表」,顺序与传入顺序一致    t3 = asyncio.create_task(fake_page_load(3, 0.3))    t4 = asyncio.create_task(fake_page_load(4, 0.1))    res = await asyncio.gather(t3, t4)    print("asyncio.gather 返回:", res, "<- 顺序与传入顺序一致")     # 直接把协程对象(不是 Task)丢给 wait 会怎样    print()    raw_coro = fake_page_load(1)    try:        await asyncio.wait([raw_coro])    except Exception as e:        print(f"{type(e).__name__}: {e}")        raw_coro.close()      # 不关掉它,解释器会警告 "coroutine was never awaited"  asyncio.run(main())
asyncio.wait asyncio.gather
返回 (done_set, pending_set),是 Task 对象的集合 结果列表
顺序 set 无序,要自己 t.result() 取 与传入顺序一致
参数 只接受 Task/Future,传协程直接 TypeError 协程、Task 都接受,自动包装
一个任务抛异常 其他任务照常跑完,异常留在 Task 里 默认立刻向外抛(可用 return_exceptions=True 改)
典型用途 要控制「等第一个完成」「超时后取消剩下的」 就是要一批结果

示例 8 先 create_task 再 wait 是必须的 —— 因为 wait 不收协程。那句 TypeError: Passing coroutines is forbidden 就是上面实测出来的,Python 3.10 之后严格执行。

第六步:为什么不用多线程#

这是本篇第三个问题,也是最值得说清的一个。用 100 个并发单元实测两者的开销:

python
import asyncioimport threadingimport time  async def fake_page_load(i, cost=0.0):    await asyncio.sleep(cost)  def thread_worker(ev):    ev.wait()          # 立刻返回,只为量「创建+启动+回收」本身的开销  async def main():    n = 100     t0 = time.monotonic()    await asyncio.gather(*(fake_page_load(i) for i in range(n)))    async_cost = time.monotonic() - t0     t0 = time.monotonic()    gate = threading.Event()    ths = [threading.Thread(target=thread_worker, args=(gate,)) for _ in range(n)]    for t in ths:        t.start()    alive = threading.active_count()   # 全部 start 完的瞬间,真实存活的 OS 线程数    gate.set()    for t in ths:        t.join()    thread_cost = time.monotonic() - t0     print(f"{n} 个协程 asyncio.gather : {async_cost * 1000:.1f} ms   OS 线程数 1(全在主线程里轮转)")    print(f"{n} 个真线程 start+join   : {thread_cost * 1000:.1f} ms   OS 线程数 {alive}(每个都是内核级线程)")    print(f"线程方案慢 {thread_cost / async_cost:.1f} 倍")  asyncio.run(main())

机制上的根本区别:

多线程 协程(asyncio)
谁决定切换 操作系统,随时可能强行打断你 你自己,只在 await 处让出
一个单元的成本 内核级线程,默认栈 8 MB 起 一个 Python 对象,几 KB
100 个单元的实测开销 35.9 ms 2.0 ms
数据竞争 需要 Lock,两个线程同时 list.append 有风险 单线程,两个 await 之间不会被打断,天然安全
调试难度 高,bug 不一定能复现(取决于线程调度时机) 低,执行顺序由 await 位置决定,可复现
适合 CPU 密集(配合多进程)、调用只有同步版的库 IO 密集:网络请求、页面加载、文件读写

最后一行是选择依据。浏览器自动化 99% 的时间在等网络、等渲染,是典型的 IO 密集,所以协程合适。

踩坑与例外#

练习#

第 3 题我的分析:能,但有前提。asyncio.to_thread(fn, *args) 会把 fn 扔到默认线程池执行,主事件循环继续跑别的任务。对 lxml 解析这种 CPU 密集块确实有效——不过 Python 的 GIL 意味着同一时刻仍只有一个线程在执行字节码,所以它省的是「不阻塞事件循环」,不是「真并行计算」。真要并行解析,得用 ProcessPoolExecutor(多进程绕过 GIL)。而且要注意线程切换本身有开销,几十毫秒的小解析放线程池反而更慢。

连出去#

附:本单元涉及的源码文件#