爬虫-代理

这篇讲什么

  • 把 urllib 的高级部分讲透:Handler 与 Opener 怎么组装、代理怎么配、cookie 怎么存怎么用,以及 HTTPError / URLError 的分支为什么要按顺序写。
  • 代理这一节重点在「怎么确认请求真的走了代理」:实测本机 ProxyHandler 对 127.0.0.1 根本不生效,原因是 Windows 注册表里的代理例外列表,requests 却不受影响。
  • cookie 这一节给出三种 CookieJar 的落盘与回读结果,并解释为什么登录后的 cookie 存到文件里是空的。

post 请求

  • 数据源分两类:抓页面、找接口、走登录的例子用公开练习站——scrape.center (《Python3 网络爬虫开发实战》作者搭的练手站)和 quotes.toscrape.com (表单与登录态沙箱);POST 语义、Set-Cookie 属性、代理取证这类必须稳定复现 403/500 的例子仍在靶站跑,输出逐字记录。

  • urllib 发 POST 只有一条规则:data 必须是 bytes。给了 data,方法自动变 POST,Content-Type 自动补 application/x-www-form-urlencoded。

    post_form.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import json
    import urllib.parse
    import urllib.request

    url = "http://127.0.0.1:8010/submit"
    form = {"name": "lilei", "token": "tok-8f2c"}
    data = urllib.parse.urlencode(form).encode() # 不 encode 会报「data should be bytes」
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 Chrome/156.0"})
    with urllib.request.urlopen(req, data=data, timeout=10) as r:
    print(r.status, json.loads(r.read()))
    1
    200 {'ok': True, 'kind': 'form', 'data': {'name': 'lilei', 'token': 'tok-8f2c'}}
  • 三种 body 的差别就在 Content-Type,服务端按它决定怎么解析:

    场景 Content-Type 怎么构造
    普通表单 application/x-www-form-urlencoded urlencode(dict).encode(),默认就是它
    JSON 接口 application/json 自己 json.dumps(obj).encode() + 显式改头
    文件上传 multipart/form-data 自己拼 boundary 很痛苦,用 requests 的 files=
    post_json.py
    1
    2
    3
    4
    5
    6
    7
    8
    import json
    import urllib.request

    body = json.dumps({"title": "新书", "price": 19.9}).encode()
    req = urllib.request.Request("http://127.0.0.1:8010/api/books", data=body,
    headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=10) as r:
    print(r.status, json.loads(r.read()))
    1
    201 {'created': {'title': '新书', 'price': 19.9}, 'kind': 'json'}
  • 表单里的隐藏字段不是装饰。靶站 /submit 要求 token 等于页面上给的值,不带或带错直接被拒:

    post_403.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import json
    import urllib.error
    import urllib.parse
    import urllib.request

    url = "http://127.0.0.1:8010/submit"
    form = {"name": "lilei", "token": "wrong"} # 故意把隐藏字段写错
    data = urllib.parse.urlencode(form).encode()
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 Chrome/156.0"})
    try:
    with urllib.request.urlopen(req, data=data, timeout=10) as r:
    print(r.status, json.loads(r.read()))
    except urllib.error.HTTPError as e:
    print(e.code, json.loads(e.read()))
    1
    403 {'ok': False, 'why': 'token 不对', 'got': {'name': 'lilei', 'token': 'wrong'}}

    真实站点上这一招叫 CSRF 令牌,正确做法是先 GET 页面把 token 取出来,再带着 cookie POST,不能硬编码。

ajax 数据在哪

  • 页面是 ajax 填出来的时候,抓 HTML 就拿不到数据。https://spa1.scrape.center/ 是现成的例子:整页只有 952 字节,片名一个都不在里面。

    ajax_static.py
    1
    2
    3
    4
    5
    6
    7
    import urllib.request

    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}
    html = urllib.request.urlopen(urllib.request.Request("https://spa1.scrape.center/",
    headers=HEADERS), timeout=20).read().decode()
    print("len:", len(html), "| 有片名?", "霸王别姬" in html, "| 只剩空壳?", '<div id=app>' in html)
    1
    len: 952 | 有片名? False | 只剩空壳? True
  • 说它「只剩空壳」是有依据的:整页只有一个 <div id=app> 挂载点和两个 script,而且这份模板是压缩过的,属性值不带引号(<div id=app> 而不是 <div id="app">),所以判空壳要取 id=app 这种短片段,别按自己习惯的写法拼完整标签去比。

  • 三条路找到真数据:

    1. DevTools 的 Fetch/XHR 面板看请求列表,找到返回 JSON 的那个地址(本例是 /api/movie,响应是 {"count": 104, "results": [...]});
    2. 直接请求接口,参数照 Payload 抄;
    3. 接口必须靠浏览器渲染才拿得到时,用 Selenium(见《爬虫-Selenium和PhantomJS》)。
  • X-Requested-With: XMLHttpRequest 是 ajax 的常见标记。scrape.center 不校验它,但很多站点会用它区分「脚本」和「页面里的 JS」,缺了它返回的可能是整页 HTML 而不是 JSON。

  • GET 与 POST 的语义差别只能在靶站看(在线练习站不接收 POST),实测同一个地址两种方法:

    method_semantics.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import json
    import urllib.request

    BASE = "http://127.0.0.1:8010"
    body = json.dumps({"title": "新书", "price": 19.9}).encode()

    with urllib.request.urlopen(BASE + "/api/books", timeout=10) as r:
    got = json.loads(r.read())
    print("GET %s -> %d | %s | data 里 %d 本书" % (
    "/api/books", r.status, sorted(got), got["data"]["total"]))

    req = urllib.request.Request(BASE + "/api/books", data=body,
    headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=10) as r:
    print("POST %s -> %d | %s" % ("/api/books", r.status, json.loads(r.read())))
    1
    2
    GET  /api/books -> 200 | ['code', 'data', 'msg'] | data 里 4 本书
    POST /api/books -> 201 | {'created': {'title': '新书', 'price': 19.9}, 'kind': 'json'}

复杂 get 与翻页

  • 翻页 URL 一般有规律,先看它是「路径型」还是「参数型」。scrape.center 的两种正好各代表一类:ssr1 是路径型 /page/2,spa1 的接口是参数型 ?limit=10&offset=10。老笔记里贴吧的 pn = (页码 - 1) * 50 属于后者。

  • 路径型的写法:把页码拼进路径,落到非 200 就停。实测抓到第 10 页为止:

    paginate.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import os
    import urllib.error
    import urllib.request

    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}
    for page in range(1, 20):
    url = "https://ssr1.scrape.center/page/%d" % page
    try:
    with urllib.request.urlopen(urllib.request.Request(url, headers=HEADERS), timeout=20) as r:
    html = r.read().decode()
    except urllib.error.HTTPError as e:
    print("第 %d 页 -> %s,停止" % (page, e.code))
    break
    name = "list_%d.html" % page
    with open(name, "wb") as f:
    f.write(html.encode("utf-8"))
    print("第 %d 页 -> 200,存 %s(%d 字节)" % (page, name, os.path.getsize(name)))
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    第 1 页 -> 200,存 list_1.html(41667 字节)
    第 2 页 -> 200,存 list_2.html(42180 字节)
    第 3 页 -> 200,存 list_3.html(41106 字节)
    第 4 页 -> 200,存 list_4.html(40050 字节)
    第 5 页 -> 200,存 list_5.html(42170 字节)
    第 6 页 -> 200,存 list_6.html(43176 字节)
    第 7 页 -> 200,存 list_7.html(42400 字节)
    第 8 页 -> 200,存 list_8.html(41964 字节)
    第 9 页 -> 200,存 list_9.html(43121 字节)
    第 10 页 -> 200,存 list_10.html(41936 字节)
    第 11 页 -> 500,停止
  • 三个要点:

    • 结束条件要判「非 200」而不是「404」:这个站第 11 页给的是 500(页码条却把 11 页列出来了),只判 404 会把异常页当正常页往下处理。
    • 路径型站点常对尾斜杠敏感:/page/2 是 200,/page/2/ 实测 404。
    • 每页都要落盘再解析,别把内容全留在内存里;出错时能接着跑。
  • 参数型的接口,「共 N 条」写在响应里,可以直接算页数,也可以用 results 是否为空收尾:

    paginate_api.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import json
    import urllib.request

    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}
    total, got, offset = None, 0, 0
    while True:
    url = "https://spa1.scrape.center/api/movie?limit=10&offset=%d" % offset
    data = json.loads(urllib.request.urlopen(urllib.request.Request(url, headers=HEADERS),
    timeout=20).read())
    total = data["count"]
    if not data["results"]:
    break
    got += len(data["results"])
    offset += 10
    print("count=%d 实际取到 %d 条,请求 %d 次" % (total, got, offset // 10))
    1
    count=104 实际取到 104 条,请求 11 次
  • 参数里出现中文必须编码,实测直接拼 ?q=三国 会 UnicodeEncodeError: 'ascii' codec can't encode characters;urlencode 之后是 ?q=%E4%B8%89%E5%9B%BD,正常返回。

URLError 与 HTTPError

  • 两者都在 urllib.error 里,且 HTTPError 是 URLError 的子类(实测 issubclass(...) 为 True)。所以 except 顺序必须是 HTTPError 在上:

    errors.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import urllib.error
    import urllib.request

    cases = [
    "http://127.0.0.1:8010/detail/9", # 404
    "http://127.0.0.1:9/", # 端口没人听
    "http://nope.invalid/", # 域名解析不了
    ]
    for url in cases:
    try:
    urllib.request.urlopen(url, timeout=5)
    except urllib.error.HTTPError as e:
    print("HTTPError", e.code, e.reason, "| 错误页", len(e.read()), "字节")
    except urllib.error.URLError as e:
    print("URLError", type(e.reason).__name__, str(e.reason)[:48])
    1
    2
    3
    HTTPError 404 Not Found | 错误页 355 字节
    URLError ConnectionRefusedError [WinError 10061] 由于目标计算机积极拒绝,无法连接。
    URLError gaierror [Errno 11001] getaddrinfo failed
  • 顺序写反的后果实测:先 except URLError 也能接住 404,但拿不到 e.code 的语义(它是 HTTPError 实例,只是被当成父类处理),分支里就没法按状态码分别重试。

  • HTTPError 本身是个「类文件对象」,e.read() 能读到错误页正文,实测 355 字节;e.headers 还能看到服务端响应头。

  • 超时不都包在 URLError 里,实测两种:

    timeout_cases.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import time
    import urllib.error
    import urllib.request

    BASE = "http://127.0.0.1:8010"
    cases = [("/slow?ms=2000", BASE + "/slow?ms=2000", 0.5), # 服务端要睡 2s
    ("10.255.255.1", "http://10.255.255.1/", 2)] # 地址不可达,卡在连接阶段
    for label, url, timeout in cases:
    t0 = time.time()
    try:
    urllib.request.urlopen(url, timeout=timeout).read()
    except urllib.error.URLError as e:
    print("%s 且 timeout=%s -> URLError: %s,等了 %.1fs" % (
    label, timeout, e.reason, time.time() - t0))
    except TimeoutError as e:
    print("%s 且 timeout=%s -> TimeoutError: %s,等了 %.1fs" % (
    label, timeout, e, time.time() - t0))
    1
    2
    /slow?ms=2000 且 timeout=0.5 -> TimeoutError: timed out,等了 0.5s
    10.255.255.1 且 timeout=2 -> URLError: timed out,等了 2.0s

    所以稳妥写法是 except (urllib.error.URLError, TimeoutError) as e:。

  • 重试不要自己 while True,先分清「值得重试」和「不值得重试」:连接类(ConnectionResetError、超时、502/503/504)值得退避重试;403/404/429 越重试越糟,429 要看 Retry-After。

Handler 与 Opener

  • urlopen() 是一个装好默认 handler 的 opener 的快捷入口;要定制行为就得自己组:

    opener.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import urllib.request

    URL = "https://ssr1.scrape.center/page/3"
    handler = urllib.request.HTTPHandler()
    opener = urllib.request.build_opener(handler)
    with opener.open(URL, timeout=20) as r:
    print("opener.open ->", r.status, len(r.read()), "字节")

    urllib.request.install_opener(opener) # 之后 urlopen 就用它
    with urllib.request.urlopen(URL, timeout=20) as r:
    print("install 后 urlopen ->", r.status, len(r.read()), "字节")
    1
    2
    opener.open -> 200 41106 字节
    install 后 urlopen -> 200 41106 字节
    • 只塞了一个 HTTPHandler 却能跑 HTTPS,是因为 build_opener() 总会自动补上缺省的那几个 handler(https、代理、cookie、重定向),你给的只是追加。
    • install_opener() 是全局的:它替换进程内 urlopen 用的那个 opener,库代码里别乱调,否则会污染同一进程里其它请求(代理、cookie 都会跟着串)。
  • 常用 handler 一览:

    Handler 作用 什么时候用
    HTTPHandler / HTTPSHandler 走 http / https 的底层通道 要给连接层加参数时
    ProxyHandler(proxies) 配代理 见下一节
    HTTPCookieProcessor(cj) 自动收发 cookie 登录态
    HTTPRedirectHandler 自动跟随 3xx 想关掉重定向时继承它并返回 None
    HTTPBasicAuth / HTTPDigestAuth 认证头 站点要 Basic/Digest 认证
    自定义 BaseHandler 挂 http_request / http_response 钩子 统一加头、统一重试、记录日志
  • 自定义 handler 的写法:继承 urllib.request.BaseHandler,方法名是 <协议>_request / <协议>_response,返回请求对象即继续,返回 None 会被跳过。

    add_header_handler.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import urllib.request

    class UAHandler(urllib.request.BaseHandler):
    def http_request(self, req):
    req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0) Chrome/156.0")
    req.add_header("X-Requested-With", "XMLHttpRequest")
    return req


    opener = urllib.request.build_opener(UAHandler())
    with opener.open("http://127.0.0.1:8010/ua", timeout=10) as r:
    print(r.status, r.read().decode().strip()[:70])
    1
    2
    3
    200 {
    "ok": true,
    "ua": "Mozilla/5.0 (Windows NT 10.0) Chrome/156.0",
    • 好处是「一处加头,全局生效」,比每个 Request 都写一遍 headers 干净。
    • 这个回显端点在靶站:要看「自己到底发了什么头」,得有个肯把请求头原样吐回来的地址。

代理

  • 正向代理替客户端出去(爬虫用的是这种),反向代理替服务端进来(nginx 挡在后端前面是这种)。

  • 三种「匿名程度」的判据就是服务端能看到什么头,实测本机代理转发时补了 Via 与 X-Forwarded-For:

    类型 目标站点看到的 实测
    透明代理 知道用了代理,也知道真实 IP Via: 1.1 spider-proxy + X-Forwarded-For: 127.0.0.1
    匿名代理 知道用了代理,不知道真实 IP 只有 Via,没有 X-Forwarded-For
    高度匿名 看起来就像普通客户端 两个头都没有
    proxy_via.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import json
    import os
    import urllib.request

    os.environ["no_proxy"] = "" # 关键,原因见下面那个坑
    opener = urllib.request.build_opener(
    urllib.request.ProxyHandler({"http": "http://127.0.0.1:8011"}))
    with opener.open("http://127.0.0.1:8010/whoami", timeout=10) as r:
    print(json.loads(r.read())["headers"])
    1
    2
    {'Accept-Encoding': 'identity', 'Host': '127.0.0.1:8010', 'User-Agent': 'Python-urllib/3.14',
    'Connection': 'close', 'Via': '1.1 spider-proxy', 'X-Forwarded-For': '127.0.0.1'}
  • ⚠️ ProxyHandler 对 127.0.0.1 默认不生效,而且不报错。实测不加 no_proxy 那行时,Via 头根本不出现——请求直连了靶站:

    proxy_bypass_check.py
    1
    2
    3
    4
    5
    import urllib.request

    print("urllib.request.getproxies() ->", urllib.request.getproxies())
    print("urllib.request.proxy_bypass('127.0.0.1') ->",
    urllib.request.proxy_bypass("127.0.0.1"))
    1
    2
    urllib.request.getproxies() -> {'no': 'localhost,.localhost,127.0.0.1,127.0.0.0/8,[::1],::1'}
    urllib.request.proxy_bypass('127.0.0.1') -> True
    • 原因:ProxyHandler.proxy_open() 里有一句 if req.host and proxy_bypass(req.host): return None,而 proxy_bypass 在环境变量 NO_PROXY 没设置时会去读 Windows 注册表的代理例外列表,本机这份列表里就有 127.0.0.1 与 127.0.0.0/8。
    • 三种解法都实测过:
      • 设 os.environ["no_proxy"] = ""(让环境变量分支接管,注册表那份就不再看);
      • 临时把 urllib.request.proxy_bypass 换成恒返回 False 的函数;
      • 目标换成不在例外列表里的地址。
    • requests 不受这条影响:它只看环境变量 NO_PROXY,本机没设,所以照常走代理(实测 Via 在)。同一份代理配置,两个库行为不一样,这是排查「代理为什么没生效」时最容易漏的一条。
  • requests 的四种写法实测:

    requests_proxies.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import requests

    BASE = "http://127.0.0.1:8010"
    P = "http://127.0.0.1:8011"
    cases = {
    "http 代理": {"http": P},
    "http+https": {"http": P, "https": P},
    "socks5h": {"http": "socks5h://127.0.0.1:8012"},
    "带账号": {"http": "http://user:pass@127.0.0.1:8011"},
    }
    for label, px in cases.items():
    r = requests.get(BASE + "/whoami", proxies=px, timeout=10)
    print(label, "->", r.status_code, "| Via:", r.json()["headers"].get("Via", "-"))
    1
    2
    3
    4
    http 代理     -> 200 | Via: 1.1 spider-proxy
    http+https -> 200 | Via: 1.1 spider-proxy
    socks5h -> 200 | Via: -
    带账号 -> 200 | Via: 1.1 spider-proxy
    • socks5h 走的是 SOCKS5(本机 8012 端口),它不补 Via,因为 SOCKS 是传输层代理,不改 HTTP 头。要装 PySocks,pip install requests[socks]。
    • socks5:// 与 socks5h:// 的差别:前者本地解析域名,后者把域名交给代理解析。爬「同一域名解析到不同 IP」的站点时这个差别会暴露出来。
    • 账号密码写在 URL 里时,urllib 会加 Proxy-Authorization: Basic dTpw(实测目标端能看到,是因为本机这个玩具代理把它原样转发了;真实代理会吃掉这个头)。
  • 浏览器/系统代理入口(用来对照,不影响代码):Chrome 在 设置 → 系统 → 打开计算机的代理设置;Windows 10/11 在 设置 → 网络和 Internet → 代理 → 代理服务器。

  • scrape.center 给配套了一个代理池 https://proxypool.scrape.center/random,一次返回一个 ip:port 纯文本,写法上是现成的教材:

    pool_once.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    import os
    import time

    import requests

    os.environ["no_proxy"] = ""
    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}
    for _ in range(3):
    proxy = requests.get("https://proxypool.scrape.center/random", timeout=25).text.strip()
    print("/random ->", repr(proxy))
    for target in ("http://ssr1.scrape.center/", "https://httpbin.org/ip"):
    t0 = time.time()
    px = {"http": "http://" + proxy, "https": "http://" + proxy}
    try:
    r = requests.get(target, proxies=px, headers=HEADERS, timeout=12)
    extra = " | 对方看到的 origin: %s" % r.json()["origin"] if "httpbin" in target else ""
    print(" %-26s -> %d %d 字节 %.2fs%s" % (target, r.status_code, len(r.content),
    time.time() - t0, extra))
    except requests.RequestException as exc:
    print(" %-26s 异常 %s %.2fs" % (target, type(exc).__name__, time.time() - t0))
    1
    2
    3
    4
    5
    6
    7
    8
    9
    /random -> '180.180.156.111:80'
    http://ssr1.scrape.center/ -> 200 41667 字节 12.83s
    https://httpbin.org/ip 异常 ConnectionError 1.25s
    /random -> '180.180.156.96:80'
    http://ssr1.scrape.center/ 异常 ProxyError 12.01s
    https://httpbin.org/ip -> 200 33 字节 6.49s | 对方看到的 origin: 180.180.156.96
    /random -> '151.245.140.36:3128'
    http://ssr1.scrape.center/ 异常 ProxyError 12.00s
    https://httpbin.org/ip 异常 ProxyError 12.02s
    • 三次抽取、六次使用,只有两次成功,而且慢(12.83 秒才拿到那个 200,正常直连不到 1 秒)。origin 那一行是判据:走通的时候对方看到的是代理的 IP,说明代理确实生效了。
    • 每次运行结果都不一样,所以「用公开代理池」的代码不能只判 status_code,必须配超时 + 失败换下一个。真要做「代理池」,正确姿势是买带 API 的私密代理,自己维护「取 IP → 试 → 打分 → 过期删除」的队列,而不是把公开列表当可靠来源。
  • 用代理时至少检查三件事:Via/X-Forwarded-For 有没有暴露、出口 IP 是不是真的换了(/whoami 里的 client 字段)、以及代理是否支持目标协议(http/https/socks5)。

  • 用代理时至少检查三件事:Via/X-Forwarded-For 有没有暴露、出口 IP 是不是真的换了(/whoami 里的 client 字段)、以及代理是否支持目标协议(http/https/socks5)。

  • HTTP 无状态,「你是谁」这件事靠 cookie 携带。服务端用响应头 Set-Cookie 下发,客户端用请求头 Cookie 带回,格式是 名字=值; 名字=值。

  • Set-Cookie 的属性决定它活多久、发给谁。实测靶站登录后拿到的那条:

    cookie_attrs.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import http.cookiejar
    import urllib.request

    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    opener.open("http://127.0.0.1:8010/login", timeout=10).read()
    c = list(cj)[0]
    print("name=%r domain=%r path=%r secure=%s discard=%s expires=%s" % (
    c.name, c.domain, c.path, c.secure, c.discard, c.expires))
    print("value 是 %d 位十六进制,每次登录都换一个" % len(c.value))
    1
    2
    name='sid' domain='127.0.0.1' path='/' secure=False discard=True expires=None
    value 是 8 位十六进制,每次登录都换一个
    • discard=True 表示这是会话级 cookie,关掉客户端就没了;靶站的 /cookies 那条带 Max-Age=3600,属性里 expires 才有具体值。
    • Path=/ 限定「只有这个路径前缀的请求才带上」;Secure 要求只在 HTTPS 下发;HttpOnly 让 JS 读不到(防 XSS 取 cookie);SameSite=Lax 限制跨站携带。
  • urllib 想自动管 cookie,要挂 HTTPCookieProcessor:

    cookiejar.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import http.cookiejar
    import json
    import urllib.request

    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    opener.open("http://127.0.0.1:8010/login", timeout=10).read()
    print("jar 里:", [(c.name, c.discard) for c in cj])
    with opener.open("http://127.0.0.1:8010/readcookie", timeout=10) as r:
    print("服务端收到:", json.loads(r.read()))
    1
    2
    jar 里: [('sid', True)]
    服务端收到: {'cookie': 'sid=56fb0be0', 'sid': '56fb0be0'}
    • 对照实验:不挂 processor、直接 urlopen 时,服务端看到的是 {'cookie': '', 'sid': ''}——urlopen 每次都是独立请求,不会替你保存也不会回带。
  • 也可以手动塞头,很多「抓包后直接抄 cookie」的脚本就是这么来的:

    1
    2
    req = urllib.request.Request("http://127.0.0.1:8010/readcookie",
    headers={"Cookie": "sid=deadbeef"})
    1
    {'cookie': 'sid=deadbeef', 'sid': 'deadbeef'}
    • 好处是简单;坏处是过期了不会自动更新,而且把会话凭据写死在代码里。⚠️ 真实站点的 cookie 等同登录态,别提交进仓库、别贴进文章。
  • 三种能落盘的 Jar,实测差别很大:

    save_cookie.py
    1
    2
    3
    4
    5
    6
    7
    8
    import http.cookiejar
    import urllib.request

    jar = http.cookiejar.MozillaCookieJar("c_mozilla.txt")
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
    opener.open("http://127.0.0.1:8010/cookies", timeout=10).read() # 这条带 Max-Age=3600
    jar.save()
    print(open("c_mozilla.txt", encoding="utf-8").read().splitlines()[-1])
    1
    127.0.0.1	FALSE	/	FALSE	1793987180	sid	da8305da
    Jar 文件格式 实测结果
    CookieJar 只在内存 进程结束就没了
    MozillaCookieJar Netscape 格式,制表符分隔 能存能回读,回读后新 opener 仍能带上 cookie
    LWPCookieJar LWP 文本格式 Set-Cookie3: sid=...; path="/"; ... 同样能存能回读
    FileCookieJar 抽象基类 save() 直接 NotImplementedError,只能用它的两个子类
    • ⚠️ 最大的坑:会话级 cookie 不会被保存。实测登录后(discard=True)jar.save() 出来的文件里除了注释行什么都没有;只有带 Expires/Max-Age 的才会落盘。想持久化就得让服务端下发持久 cookie,或者自己把值写进配置。
    • save() 要显式调用,程序不会替你存;load() 默认 ignore_discard=False,遇到过期条目会跳过。
  • 完整链路:GET 登录页(拿会话 cookie 和 CSRF token)→ 带着 cookie POST 凭据 → 保持同一 opener → GET 登录后才有的页面。用 quotes.toscrape.com 这个专门给爬虫练手的沙箱实测(它的登录不校验账号口令,只校验 token,正好看清 token 的作用):

    csrf_login.py
    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
    import http.cookiejar
    import re
    import urllib.parse
    import urllib.request

    SITE = "https://quotes.toscrape.com"
    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}


    def new_opener():
    cj = http.cookiejar.CookieJar()
    return urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)), cj


    def try_login(with_token):
    opener, cj = new_opener()
    html = opener.open(urllib.request.Request(SITE + "/login", headers=HEADERS),
    timeout=20).read().decode()
    token = re.search(r'name="csrf_token" value="([^"]+)"', html).group(1)
    form = {"username": "admin", "password": "password", "next": "/"}
    if with_token:
    form["csrf_token"] = token
    req = urllib.request.Request(SITE + "/login", data=urllib.parse.urlencode(form).encode(),
    headers=dict(HEADERS, Referer=SITE + "/login"))
    with opener.open(req, timeout=20) as r:
    body = r.read().decode()
    return r.status, r.geturl(), 'href="/logout"' in body, len(cj)


    print("不带 token ->", try_login(False))
    print("带上 token ->", try_login(True))
    1
    2
    不带 token -> (200, 'https://quotes.toscrape.com/login', False, 1)
    带上 token -> (200, 'https://quotes.toscrape.com/', True, 1)
    • 状态码帮不了你:两种都是 200。判据只能是落地页——带对 token 才跳到首页、页面里才出现 /logout 那个链接。
    • token 与会话是绑死的:csrf_token 的值长度 52,是从这一次 GET 的页面里正则出来的,换个 opener 就得重新取,不能复用上一轮的。
  • 验证码这一步只能在靶站演示(在线站不会把答案印在页面上)。靶站 /login 的实测:

    login_captcha.py
    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
    import http.cookiejar
    import re
    import urllib.error
    import urllib.parse
    import urllib.request

    BASE = "http://127.0.0.1:8010"
    PATTERN = r"不会写出来):(\d{4})"


    def login_page():
    """开一个新会话取登录页,返回 (opener, 验证码, jar 里的 cookie 名)。"""
    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    html = opener.open(BASE + "/login", timeout=10).read().decode()
    return opener, re.search(PATTERN, html).group(1), [c.name for c in cj]


    opener, cap, names = login_page()
    print("验证码是 %d 位数字 | cookie: %s" % (len(cap), names))
    print("换一个会话再取一次登录页,两次验证码相同吗:", login_page()[1] == cap)


    def login(captcha):
    form = {"username": "lilei", "password": "password", "captcha": captcha}
    req = urllib.request.Request(BASE + "/login", data=urllib.parse.urlencode(form).encode())
    try:
    with opener.open(req, timeout=10) as r:
    return r.status, "登录成功" in r.read().decode()
    except urllib.error.HTTPError as e:
    return e.code, "登录失败" in e.read().decode()


    print("错验证码 ->", login("0000"))
    print("对验证码 ->", login(cap))
    1
    2
    3
    4
    验证码是 4 位数字 | cookie: ['sid']
    换一个会话再取一次登录页,两次验证码相同吗: False
    错验证码 -> (401, True)
    对验证码 -> (200, True)
    • 验证码和 sid 是绑在一起的:换一个 sid(重新 GET 登录页)验证码就变了,所以「取图 → 识别 → 提交」必须在同一个 opener 里连续完成。
    • 密码字段很多站点在前端做哈希(老笔记里那串 64 位十六进制就是 SHA-1 的结果),要先看懂它的 JS 才能构造,这类站点通常直接上浏览器方案更省事。
    • 识别验证码本身是另一件事,本机用 Tesseract 与 ddddocr 的实测写法见《爬虫-Requests》的验证码一节。
  • 判断「登录成功」不要只看状态码,可靠做法是取一个登录后才有的元素作为判据,上面那段用的就是 href="/logout"。

  • 判断「登录成功」不要只看状态码:很多站点登录失败也返回 200,只是页面里写着「用户名或密码错误」。可靠做法是取一个登录后才有的元素(比如个人主页链接、余额数字)作为判据。

参考

本文结束 感谢您的阅读
正在加载今日诗词....