Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面

系列规划回顾:

  • 第一篇:HTTP 基础、requests、四种解析方式、完整翻页爬虫
  • 第二篇(本篇) :反爬分层对抗、Cookie/Session、代理池与重试、线程池与异步并发、Selenium / Playwright、F12 抓包找接口
  • 第三篇:数据存储(CSV/MySQL/MongoDB)、Scrapy 框架、增量去重、日志与部署、合规收尾
  • 如仍不足,追加扩展篇:APP 抓包、JS 逆向入门、验证码识别、分布式爬虫

一、为什么你的爬虫"一上服务器就 403"

第一篇的代码在本地跑得好好的,一放到服务器上,很快就出现 403、429、验证码、空白页、甚至 200 但数据全是假的。原因通常不是某一个点,而是一整套风控机制在同时工作。反爬系统往往按层级逐层检测,你的爬虫会卡在最先没通过的那一层:

层级 检测内容 典型症状 对应手段
1 请求头、UA、Accept 403,直接拒绝 伪造完整浏览器请求头
2 请求频率、顺序 429,或 200 但数据异常 随机延时、乱序、批次停顿
3 IP 累计请求量 跑一段时间后全面超时 代理池、IP 轮换
4 验证码 跳转验证页 降触发率,人工介入
5 JS 指纹(Canvas/WebGL) 无头浏览器被识别 Playwright stealth
6 行为轨迹 数据量大后仍被封 模拟跳转链、随机操作

这张分层表来自一份系统的反爬排障手册,思路很清晰:哪里被拦,就从对应层级往下解决 。本篇基本按这个顺序展开,但在第 4 层(验证码)只讲"检测和降低触发率",不涉及绕过验证码------那已经超出了合规爬虫的边界。


二、第一层:请求头------不要"裸奔"

2.1 先看看你自己的请求长什么样

python 复制代码
import requests
r = requests.get("https://example.com")
print(dict(r.request.headers))

如果你看到的是:

text 复制代码
{'User-Agent': 'python-requests/2.31.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', ...}

那这个请求大概率会被直接拦截。python-requests、curl、Scrapy 等字符串在很多风控系统的黑名单里,匹配到就拒绝,根本不需要做频率分析。

2.2 一套能用的请求头构造

不要只改 User-Agent。Accept、Accept-Language、Referer、Sec-Fetch-* 这一组字段需要互相自洽,单改一个反而会成为破绽。

python 复制代码
import random

UA_LIST = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
]

def build_headers(referer=None, is_ajax=False):
    ua = random.choice(UA_LIST)
    if is_ajax:
        return {
            "User-Agent": ua,
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Referer": referer or "https://example.com/",
            "X-Requested-With": "XMLHttpRequest",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
        }
    return {
        "User-Agent": ua,
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Accept-Encoding": "gzip, deflate, br",
        "Referer": referer or "https://example.com/",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
    }

这段构造参考了实际反爬对抗中常用的方案:区分页面请求 和 XHR 请求 两套头,Referer 按上下文传入,UA 从池中随机选取。

进阶提示 :Cloudflare、Akamai 等会校验 TLS 指纹 (JA3/JA4),Python 标准 requests 的 TLS 握手特征和真实浏览器不同。对这类目标,可以考虑 curl_cffi 库,它在底层模拟了浏览器 TLS 指纹。


三、第二层:频率------让请求"像人"

固定 time.sleep(1) 有两个问题:一是效率低,二是固定间隔比随机间隔更容易被算法识别------哪有真人连续几小时每隔精确 1 秒点一次网页。

3.1 随机延时 + 批次停顿

python 复制代码
import time, random

def human_delay(min_s=1.5, max_s=4.0):
    delay = random.uniform(min_s, max_s)
    if random.random() < 0.05:          # 5% 概率模拟"读得久了一点"
        delay += random.uniform(15, 45)
    time.sleep(delay)

def batch_delay():
    time.sleep(random.uniform(30, 90))   # 每 50 个请求左右停一大下

使用时配合计数:

python 复制代码
for i, target in enumerate(targets):
    # ... 请求和解析 ...
    human_delay()
    if (i + 1) % 50 == 0:
        batch_delay()

3.2 打乱请求顺序

顺序爬取会形成一条"从第 1 页直线走到第 5000 页"的完美轨迹,这在风控系统眼里非常显眼。把目标列表 random.shuffle() 一下,成本极低,但能打散频率特征。


四、第三层:IP------别一个 IP 薅到死

4.1 代理类型怎么选

类型 价格 存活率 被识别概率 场景
机房代理 低 低 高 不推荐
住宅代理 中 高 低 大多数电商、内容平台
4G/移动代理 高 极高 极低 强防护平台

免费代理 99% 要么已经死掉,要么本身就是蜜罐,不要在正式项目中使用。

4.2 一个带有效性统计的轻量代理池

直接 random.choice(proxies) 是不够的------你需要记录哪个代理成功、哪个失败、哪个已经彻底不可用。

python 复制代码
from dataclasses import dataclass

@dataclass
class ProxyStats:
    url: str
    success: int = 0
    fail: int = 0
    banned: bool = False

    @property
    def fail_rate(self):
        total = self.success + self.fail
        return self.fail / total if total > 0 else 0.0


class SimpleProxyPool:
    def __init__(self, proxy_urls):
        self.proxies = [ProxyStats(url=u) for u in proxy_urls]
        self._index = 0

    def current(self):
        available = [p for p in self.proxies if not p.banned and p.fail_rate < 0.5]
        if not available:
            for p in self.proxies:       # 全部被 ban 时重置,给一轮复活机会
                p.banned = False
            available = self.proxies
        if self._index >= len(available):
            self._index = 0
        return available[self._index]

    def rotate(self):
        self._index += 1

    def mark_success(self):
        self.current().success += 1

    def mark_fail(self, ban=False):
        p = self.current()
        p.fail += 1
        if ban:
            p.banned = True
        self.rotate()

    def make_session(self):
        import requests
        s = requests.Session()
        p = self.current()
        s.proxies = {"http": p.url, "https": p.url}
        return s

关键设计:失败率超过 50% 的代理自动降权;返回 403 / 验证码页时直接 ban=True 并轮换。逻辑参考了一份完整代理池实现的思路。

4.3 请求循环里的状态码分流

python 复制代码
for target_id in targets:
    session = pool.make_session()
    try:
        r = session.get(url, headers=build_headers(), timeout=15)
        if r.status_code == 200:
            if is_captcha_page(r.text, r.url):
                pool.mark_fail(ban=True)
                time.sleep(random.uniform(15, 30))
                continue
            parse_and_save(r.text)
            pool.mark_success()
        elif r.status_code == 403:
            pool.mark_fail(ban=True)
            time.sleep(random.uniform(8, 20))
        elif r.status_code == 429:
            time.sleep(random.uniform(45, 90))   # 429 是明确的"太快了"信号
        else:
            pool.mark_fail()
    except requests.exceptions.ProxyError:
        pool.mark_fail(ban=True)
    except requests.exceptions.Timeout:
        pass          # 超时不 ban 代理,但也不记成功

429 单独处理很重要:它说明频率策略失效了,应该停下来等,而不是继续砸。


五、Cookie 与 Session:把"登录态"带在身上

5.1 requests.Session 已经帮你做了大半

Session 会自动保存服务器 Set-Cookie 下发的 Cookie,并在后续请求中自动带上。这意味着用同一个 Session 完成登录和后续请求,不需要手动拼 Cookie 头。

python 复制代码
import requests

s = requests.Session()
s.headers.update(build_headers())

# 第一步:必要时先访问首页,拿到初始 Cookie
s.get("https://quotes.toscrape.com/")

# 第二步:POST 登录
login_data = {"username": "your_user", "password": "your_pass"}
r = s.post("https://quotes.toscrape.com/login", data=login_data, timeout=10)

# 第三步:后续请求自动携带登录 Cookie
profile = s.get("https://quotes.toscrape.com/", timeout=10)

注意:真实网站的登录通常还涉及 CSRF Token 或动态参数,需要先从登录页 HTML 中解析出 token 再一并 POST。思路和解析表单一样,先用 BeautifulSoup/XPath 取出隐藏字段即可。

如果不想每次运行都重新登录,可以把 Cookie 存到文件:

python 复制代码
import json

# 保存
with open("cookies.json", "w") as f:
    json.dump(s.cookies.get_dict(), f)

# 加载
with open("cookies.json") as f:
    cookies = json.load(f)
s.cookies.update(cookies)

注意:Cookie 有有效期,生产环境需要检测登录态是否失效(比如请求某个需要登录的页面,看是否被重定向到登录页),失效时自动重新登录。


六、失败处理:重试与指数退避

网络抖动、代理切换、临时 5xx 都不应该让整个任务崩溃。urllib3 的 Retry 可以挂在 requests 的 HTTPAdapter 上,实现指数退避:第 1 次等 1 秒,第 2 次等 2 秒,第 3 次等 4 秒......

python 复制代码
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def make_robust_session():
    s = requests.Session()
    retry = Retry(
        total=3,
        backoff_factor=1,                       # 退避因子,实际等待 = factor * (2 ** (n-1))
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET", "POST"],
    )
    adapter = HTTPAdapter(max_retries=retry)
    s.mount("http://", adapter)
    s.mount("https://", adapter)
    return s

指数退避是处理限流和临时服务器过载的标准做法,单条 URL 重试 3~5 次通常足够。不要对 403 和 404 盲目重试------403 是策略性拒绝,重试只会浪费 IP 信誉。


七、并发:从"一个一个爬"到"一批一批爬"

第一篇的循环是串行的:请求 → 等响应 → 解析 → 下一个。如果每个请求平均耗时 1 秒,1000 个页面就要接近 17 分钟。爬虫是典型的 I/O 密集型任务,等待网络的时间远多于 CPU 计算,非常适合并发。

7.1 线程池:ThreadPoolExecutor(最容易上手)

python 复制代码
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed

def fetch(url):
    try:
        r = requests.get(url, headers=build_headers(), timeout=10)
        r.raise_for_status()
        return url, r.text
    except Exception as e:
        return url, None

with ThreadPoolExecutor(max_workers=10) as pool:
    futures = {pool.submit(fetch, u): u for u in urls}
    for fut in as_completed(futures):
        url, html = fut.result()
        if html:
            parse(html)

max_workers=10 意味着同时最多 10 个请求在飞 。线程池适合"几百到几千个 URL"的量级,改动成本极低。但要注意:多线程共享同一个 requests.Session 不一定线程安全,一个简单的做法是每个线程创建自己的 Session,或者使用无 Session 的短连接。

7.2 异步:aiohttp + asyncio(真正的高并发)

当 URL 数量到万级,线程池的线程切换开销开始显现,aiohttp 的事件循环方案更合适。下面是一个带并发上限的异步爬虫骨架:

python 复制代码
import asyncio
import aiohttp

async def fetch(session, url, semaphore):
    async with semaphore:                    # 信号量控制同时进行的请求数
        try:
            async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as resp:
                text = await resp.text()
                return {"url": url, "status": resp.status, "text": text}
        except Exception as e:
            return {"url": url, "error": str(e)}

async def crawl(urls, max_concurrency=50):
    semaphore = asyncio.Semaphore(max_concurrency)
    connector = aiohttp.TCPConnector(limit=100, limit_per_host=10)
    headers = {"User-Agent": random.choice(UA_LIST)}

    async with aiohttp.ClientSession(connector=connector, headers=headers) as session:
        tasks = [asyncio.create_task(fetch(session, u, semaphore)) for u in urls]
        results = await asyncio.gather(*tasks)
    return results

results = asyncio.run(crawl(urls, max_concurrency=50))

这里有三层控制,缺一不可:

  • Semaphore(50):业务层面的并发上限,同时只有 50 个请求在跑;
  • TCPConnector(limit=100, limit_per_host=10):连接池层面,限制总连接数和单主机连接数;
  • ClientTimeout(total=10):每个请求的总超时。

一个常见的坑 :asyncio.gather 一次性把几万个任务全部创建出来,即使有 Semaphore,内存和调度压力也很大。生产代码通常用 asyncio.Queue + 固定数量的 worker 协程来消费任务,或者分批 gather。

7.3 线程池 vs aiohttp:怎么选

ThreadPoolExecutor aiohttp + asyncio
上手难度 低,改几行 中,需要理解 async/await
适合量级 几百 ~ 几千 几千 ~ 几万
可控性 一般 高(连接池、信号量、超时精细控制)
与现有同步代码兼容 极好 需要改造为异步

建议:先用线程池解决 80% 的场景;确实需要更高吞吐时,再迁移到 aiohttp。


八、动态页面:当 HTML 里根本没有数据

第一篇说过,requests 拿到的 resp.text 是服务器返回的原始 HTML。如果页面数据是由 JavaScript 在浏览器里渲染出来的,你拿到的就是一个空壳。两条路:找后台接口 (第九节),或者用浏览器自动化工具让它真的"打开浏览器"。

8.1 Selenium:等待是核心

Selenium 最常见的问题不是定位不到元素,而是时机不对 。driver.get() 在 load 事件触发时就返回了,但 AJAX 数据可能还没回来。

不要用 time.sleep()。用显式等待:

python 复制代码
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
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless=new")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])

driver = webdriver.Chrome(options=options)
driver.get("https://example.com/dynamic")

wait = WebDriverWait(driver, 15)
rows = wait.until(
    EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.item"))
)
for row in rows:
    print(row.text)

driver.quit()

永远不要混用隐式等待和显式等待 ,两者叠加会导致不可预测的超时行为。--disable-blink-features=AutomationControlled 和 excludeSwitches 是 Selenium 中最基础的降低自动化特征的手段,但它只能掩盖最粗浅的检测,面对 Cloudflare 级别的风控远远不够。

8.2 Playwright:更现代,但"stealth"不是内置的

Playwright 在等待机制上更友好(很多操作自带 auto-wait),API 也更现代。但需要明确一点:Playwright 本身没有 stealth 功能 。"Playwright stealth"指的是第三方包 playwright-stealth,它在页面脚本执行之前修补浏览器指纹泄露。

python 复制代码
from playwright.sync_api import sync_playwright
from playwright_stealth import Stealth

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    stealth = Stealth()
    stealth.apply_stealth_sync(page)

    page.goto("https://example.com/dynamic", wait_until="networkidle")
    page.wait_for_selector("div.item", timeout=15000)

    items = page.query_selector_all("div.item")
    for item in items:
        print(item.inner_text())

    browser.close()

wait_until="networkidle" 在网络基本空闲后再继续,配合 wait_for_selector 是动态页面的稳妥等待组合。playwright-stealth 会修补 navigator.webdriver、Chrome API 缺失、WebGL 指纹等信号,但它只修复浏览器层面的信号,不解决 IP 信誉、TLS 指纹和行为分析。

8.3 动态渲染的代价

浏览器自动化每个实例占用内存高(Selenium/Playwright 一个 Chromium 实例轻松 300MB+),速度远慢于纯 HTTP 请求,且在大规模场景下成本急剧上升。能用接口解决的,不要用浏览器。浏览器自动化是"最后手段",不是"首选方案"。


九、F12 抓包:找到藏在背后的 JSON 接口

很多"动态页面"其实有干净的数据接口,只是你没看到。找到它,就可以回到 requests 的世界,用第一篇文章的方法高效抓取。

9.1 标准流程

  1. 打开目标页面,按 F12 → Network(网络) 面板;
  2. 勾选 Preserve log(保留日志),防止翻页跳转后请求记录被清空;
  3. 点击 XHR / Fetch 筛选,只看异步数据请求;
  4. 执行触发数据的操作:翻页、滚动、点击"加载更多"、搜索;
  5. 观察新增了哪个请求 ,点击它,看 Response 是不是结构化的 JSON;
  6. 检查 Headers 里的请求 URL、方法(GET/POST)、参数、以及必要的请求头。

9.2 一个实战判断

如果你在 XHR 列表里看到一个请求,Response 里整齐地排列着商品名称、价格、ID,那这就是数据接口 。直接复制它的 URL、参数和关键请求头,用 requests 模拟即可:

python 复制代码
def fetch_api(page):
    url = "https://example.com/api/products"
    params = {"page": page, "size": 20}
    headers = build_headers(referer="https://example.com/products", is_ajax=True)
    r = requests.get(url, params=params, headers=headers, timeout=10)
    r.raise_for_status()
    return r.json()          # 直接拿到结构化数据

这条思路来自 Ajax 分页爬取的标准做法:接口 URL 里通常有 page/size/offset 这类参数,翻页就是改参数。

9.3 接口找不到时

有些接口的参数带签名、时间戳、token,或者返回数据被加密/混淆。这时:

  • 先在 Sources 面板全局搜索参数名(如 sign、nonce、token),看 JS 里怎么生成的;
  • 如果签名逻辑复杂,再考虑 JS 逆向或浏览器自动化------但这已经进入扩展篇的范围。

十、把本篇的东西组装起来:一个"能活下来"的爬虫骨架

下面是一个把请求头轮换、随机延时、代理池、重试、状态码分流串在一起的最小骨架。它不是生产级代码,但结构可以直接扩展:

python 复制代码
import time, random, requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

class RobustCrawler:
    def __init__(self, proxy_pool=None, min_delay=1.5, max_delay=4.0):
        self.proxy_pool = proxy_pool
        self.min_delay = min_delay
        self.max_delay = max_delay

    def _session(self):
        s = requests.Session()
        retry = Retry(total=3, backoff_factor=1,
                      status_forcelist=[429, 500, 502, 503, 504])
        adapter = HTTPAdapter(max_retries=retry)
        s.mount("http://", adapter)
        s.mount("https://", adapter)
        if self.proxy_pool:
            p = self.proxy_pool.current()
            s.proxies = {"http": p.url, "https": p.url}
        return s

    def get(self, url, referer=None, is_ajax=False):
        s = self._session()
        try:
            r = s.get(url, headers=build_headers(referer, is_ajax), timeout=15)
            if r.status_code == 429:
                time.sleep(random.uniform(45, 90))
                return None
            r.raise_for_status()
            if self.proxy_pool:
                self.proxy_pool.mark_success()
            return r
        except requests.exceptions.ProxyError:
            if self.proxy_pool:
                self.proxy_pool.mark_fail(ban=True)
            return None
        except requests.exceptions.RequestException:
            return None
        finally:
            time.sleep(random.uniform(self.min_delay, self.max_delay))

使用方式:

python 复制代码
pool = SimpleProxyPool(["http://user:pass@proxy1:8080", "http://user:pass@proxy2:8080"])
crawler = RobustCrawler(proxy_pool=pool)

html = crawler.get("https://example.com/list", referer="https://example.com/")
if html:
    parse(html)

这个骨架已经覆盖了反爬第 1~3 层和第 8 层(重试与指数退避),日常 80% 的中低防护站点足够应对。


十一、本篇小结 & 第三篇预告

你现在应该掌握:

  • ✅ 反爬的分层逻辑:请求头 → 频率 → IP → 验证码 → 指纹 → 行为
  • ✅ 完整请求头的构造,以及 Sec-Fetch-* 的自洽性
  • ✅ 随机延时 + 批次停顿 + 乱序,替代固定 sleep
  • ✅ 代理池的轮换、有效性统计、失败淘汰
  • ✅ requests.Session 管理 Cookie / 登录态,以及持久化
  • ✅ Retry + HTTPAdapter 实现指数退避
  • ✅ ThreadPoolExecutor 和 aiohttp + Semaphore + TCPConnector 两种并发方案
  • ✅ Selenium 显式等待、Playwright stealth 的正确用法与边界
  • ✅ F12 抓包定位 XHR/JSON 接口的完整流程

下一篇《工程篇》将解决:

  1. 数据落盘:CSV / JSON / MySQL / MongoDB 的选择与代码
  2. Scrapy:把爬虫从"脚本"升级为"框架",理解 Spider / Item / Pipeline / Middleware
  3. 增量爬取与去重:如何只抓"新的"数据
  4. 日志、监控与断点续跑
  5. 部署与调度:cron / 定时任务 / 容器化
  6. 合规收尾:robots.txt、频率伦理、数据边界

建议动手把第十节的骨架跑起来,并尝试接入一个真实的代理(或至少用 httpbin.org/ip 验证代理是否生效),再把第一篇的 quotes 爬虫改造成线程池版本。下一篇见。


下一篇文件命名建议 :Python爬虫从入门到实战(三):工程篇.md

相关推荐
VIP_CQCRE12 分钟前
GPT Image 2.6 动态表情交付别只发预览:GIF 文件校验、哈希清单与下载排错
图像处理·人工智能·python·gif
2601_9679873717 分钟前
使用 NumPy 和 Python 实现梯度下降
python·机器学习·线性回归·numpy·梯度下降
BD_Marathon1 小时前
Jupyter魔法命令
ide·python·jupyter
S_WEAN1 小时前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
词却1 小时前
Python 正则表达式实战:使用 re 模块提取符合条件的字符串
python·正则表达式
星落梦生2 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
汤姆宝库2 小时前
视觉语言模型的实现:LLaVA式投影与指令微调
python·深度学习·语言模型
2601_9679791212 小时前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
FRing0312 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2