爬虫-基本入门

这篇讲什么

  • 爬虫在技术上就两件事:用程序发 HTTP 请求拿到内容,再从内容里把想要的字段挑出来。这篇先把「HTTP 报文到底长什么样」用真实字节摊开看一遍。
  • 顺手把 Python 标准库 urllib 的五个子模块逐个跑一遍:request 发请求、parse 拆 URL、error 接异常、response 读响应、robotparser 看站点规矩。
  • 最后落到两个能直接抄走的最小例子:一个用 urllib 抓在线练习站的列表页,一个带 token 的 POST 表单,并解释为什么服务端一眼就能认出你不是浏览器。

爬虫是什么

  • 本篇的输出都是本机实跑的结果,数据源分两类:

    • 抓内容的例子一律用公开练习站 scrape.center——《Python3 网络爬虫开发实战》作者搭的练习站,专门给爬虫练手,ssr1 子站是服务端渲染的电影列表,不用浏览器就能拿到完整 HTML。
    • 协议级的例子(裸报文、状态码、gzip、重定向、cookie、表单被拒、自签证书)留在本机靶站:一个只用标准库写的小站点。在线站不会稳定地给你 500、403 和一张自签证书,这类演示只能自己搭。
  • 环境基线:Python 3.14.10 + requests 2.34.2 + mitmproxy 12.3.1。

  • 一句话:爬虫就是一个「不显示页面的浏览器」。浏览器做的事是「解析 URL → 建 TCP 连接 → 发 HTTP 请求 → 收响应 → 渲染」,爬虫只需要前三步加一步「从响应里取数据」。

  • 三类爬虫的差别在「抓多少」和「抓多深」:

    类型 目标 产物 典型做法
    通用爬虫 尽可能覆盖全网 倒排索引、网页库 从种子 URL 出发顺着链接爬,先存后处理
    聚焦爬虫 某一类具体数据 结构化字段(表格里的那些列) 只跟进与主题相关的链接,边爬边解析
    接口爬虫 某个 JSON 接口 直接落库 找到 ajax 背后的接口,绕开 HTML
  • 通用爬虫怎么发现新站点,靠的是三件事:站点主动提交 URL、友情链接把链接带进图里、以及与 DNS 服务商合作拿到新注册域名。这三件事聚焦爬虫都用不上,聚焦爬虫的种子 URL 是你自己给的。

  • 聚焦爬虫的三步固定不变:

    1. 给一个 URL;
    2. 写程序模拟浏览器访问它,拿到 HTML 或 JSON;
    3. 按规则解析,把字段取出来存好。
  • 网页能被程序处理的前提有三条,也正是这三条决定了爬虫的写法:每个页面有唯一 URL、内容是 HTML(或 JSON)结构、传输走 HTTP/HTTPS。

网站原理

robots.txt 是约定,不是开关

  • urllib.robotparser 能读它,实测靶站的 User-agent: * + Disallow: /private/:

    probe_robots.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    from urllib.robotparser import RobotFileParser

    rp = RobotFileParser()
    rp.set_url("http://127.0.0.1:8010/robots.txt")
    rp.read()
    print(rp.can_fetch("MyBot", "http://127.0.0.1:8010/private/x"))
    print(rp.can_fetch("MyBot", "http://127.0.0.1:8010/list"))
    print(rp.can_fetch("Googlebot", "http://127.0.0.1:8010/private/x"))
    print(rp.crawl_delay("MyBot"), rp.request_rate("MyBot"))
    1
    2
    3
    4
    False
    True
    False
    None None
  • ⚠️ 它只约束「愿意遵守的爬虫」。同一个靶站,直接 urlopen("http://127.0.0.1:8010/private/x") 照样返回 200 —— 服务端没拦,是 robots.txt 在「劝」。

  • 真站点上三种情况都要见过(实测):

    • https://ssr1.scrape.center/robots.txt -> 404,返回 179 字节的 Django 404 页;robotparser 解析出 0 条规则、allow_all=True,can_fetch 怎么问都是 True。
    • https://spa1.scrape.center/robots.txt -> 200,但 Content-Type: text/html、952 字节,正文是前端页面的 HTML 外壳;同样解析出 0 条规则,此时 allow_all=False,can_fetch 却仍是 True。
    • 所以判断「这站有没有 robots」不能只看状态码:要看 Content-Type 和正文首行,解析不出规则时 robotparser 的默认值并不表示「允许」。
  • 另一个实测坑:set_url() 指到一个普通 HTML 页面时,read() 不报错,can_fetch() 一律返回 True。所以别把「返回 True」当成「站点没有规则」,要确认自己取到的确实是 robots.txt。

  • 实践上的底线:只抓公开页面、带上可识别的 UA、控制并发和频率、涉及登录态与个人隐私的数据不碰。判断标准不是「能不能抓到」,而是「抓到是否合规」。

HTTP 请求长什么样

  • 别背概念,直接看字节。用裸 socket 手写一个请求发给靶站:

    raw_request.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import socket

    req = ("GET /detail/1 HTTP/1.1\r\n"
    "Host: 127.0.0.1:8010\r\n"
    "User-Agent: raw-socket/1.0\r\n"
    "Connection: close\r\n"
    "\r\n") # 这个空行是「请求头到此为止」的记号
    s = socket.create_connection(("127.0.0.1", 8010), timeout=10)
    s.sendall(req.encode())
    data = b""
    while True:
    chunk = s.recv(4096)
    if not chunk:
    break
    data += chunk
    s.close()
    head, _, body = data.partition(b"\r\n\r\n")
    print(head.decode())
    print(repr(body[:60]))
    1
    2
    3
    4
    5
    6
    HTTP/1.1 200 OK
    Server: SpiderTarget/1.0 Python/3.14.10
    Date: Fri, 06 Nov 2026 16:32:17 GMT
    Content-Type: text/html; charset=utf-8
    Content-Length: 804
    b'<!doctype html>\n<html lang="zh">\n<head>\n<meta charset="utf-8'
  • 一个请求报文就是四段,顺序固定:请求行(方法 + 路径 + 版本)、请求头、一个空行、请求体(GET 通常没有)。响应同理:状态行、响应头、空行、响应体。

HTTP 请求报文

  • 空行不是排版。服务端是靠它判断「头说完了」,实测把最后那个 \r\n 去掉,/echo 就永远等不到请求结束,客户端只能超时。
  • 请求行里的 URL 只是「路径 + 查询串」,主机和端口在 Host 头与 TCP 连接里。HTTP/1.1 规定 Host 必带,但服务端不一定校验:实测裸 socket 去掉 Host 头,靶站照样回 HTTP/1.1 200 OK。虚拟主机靠它分流,所以自己写请求时该带还是要带,只是别指望对方帮你报错。

九种方法在真实服务上的结果

  • 靶站的 /echo 会原样报告它收到的方法,实测:

    方法 靶站返回 说明
    GET 200,正文里 "method": "GET" 只取资源,参数在 URL 上
    HEAD 200,正文 0 字节 与 GET 同样的头,没有体,用来探大小和修改时间
    POST 405 提交数据;靶站把 /echo 只挂在 GET 分支上,专门留了这条反例
    PUT 200,"body_kind": "form" 整体替换;带 data 时 Request 会自动用它
    PATCH 200,"body_kind": "form" 局部更新
    DELETE 200,"method": "DELETE" 删除资源
    OPTIONS 200,响应头带 Allow: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS 问服务端支持哪些方法
    TRACE 501 Python 的 http.server 没实现 do_TRACE,方法名本身是合法的
    FOO 501 自定义方法:服务端不认就 501,不是 405
    methods.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import urllib.request

    for m in ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"]:
    data = b"x=1" if m in ("POST", "PUT", "PATCH") else None
    req = urllib.request.Request("http://127.0.0.1:8010/echo", data=data, method=m)
    try:
    with urllib.request.urlopen(req, timeout=10) as r:
    print("%-7s %s %d 字节" % (m, r.status, len(r.read())))
    except Exception as e:
    print("%-7s %s" % (m, e))
    1
    2
    3
    4
    5
    6
    7
    8
    GET     200 106 字节
    HEAD 200 0 字节
    POST HTTP Error 405: Method Not Allowed
    PUT 200 152 字节
    PATCH 200 154 字节
    DELETE 200 109 字节
    OPTIONS 200 108 字节
    TRACE 501 Unsupported method ('TRACE')
  • 405 与 501 的分工:405 是「这个 URL 不接受该方法」,501 是「这个服务器压根不认识该方法」。

URL 的六个部分

  • urllib.parse.urlparse() 实测一条带端口、带 ;参数、带中文查询串和锚点的 URL:

    parse_url.py
    1
    2
    3
    4
    5
    6
    from urllib.parse import urlparse

    u = "https://www.example.com:8443/path/to/page;v=1?name=%E5%BC%A0%E4%B8%89&age=25#frag"
    p = urlparse(u)
    print(p)
    print(p.hostname, p.port)
    1
    2
    ParseResult(scheme='https', netloc='www.example.com:8443', path='/path/to/page', params='v=1', query='name=%E5%BC%A0%E4%B8%89&age=25', fragment='frag')
    www.example.com 8443
    • <协议>://<主机>:<端口>/<路径>?<查询>#<锚点>;端口省略时用该协议默认端口(HTTP 80、HTTPS 443)。
    • netloc 里带端口,hostname/port 是分开的两个值,取主机名用 hostname 更稳。
    • params 这个字段几乎见不到,它是 urlparse 相对 urlsplit 多出来的一步拆分:同一个 URL 用 urlsplit 得到的 path 是 /path/to/page;v=1。爬虫里统一用 urlsplit 或 urlparse 都行,但别指望 params 有值。

URL 的组成

  • 拼相对链接必须用 urljoin,手写字符串拼接是错的(实测六种):

    urljoin_demo.py
    1
    2
    3
    4
    5
    from urllib.parse import urljoin

    base = "http://a.com/p/base.html"
    for rel in ["subdir/page.html", "../other.html", "/abs", "?q=1", "http://other.com/x", "//cdn.x/a.css"]:
    print("%-22r -> %s" % (rel, urljoin(base, rel)))
    1
    2
    3
    4
    5
    6
    'subdir/page.html'     -> http://a.com/p/subdir/page.html
    '../other.html' -> http://a.com/other.html
    '/abs' -> http://a.com/abs
    '?q=1' -> http://a.com/p/base.html?q=1
    'http://other.com/x' -> http://other.com/x
    '//cdn.x/a.css' -> http://cdn.x/a.css
    • ?q=1 只换查询串、//cdn.x/a.css 只换主机,这两种写法拼字符串一定会错。

常见请求头

  • 靶站的 /whoami 会把收到的头原样吐回来,三个客户端实测对比:

    客户端 发出去的头
    urllib.request.urlopen Accept-Encoding: identity、Host、User-Agent: Python-urllib/3.14、Connection: close
    requests.get Host、User-Agent: python-requests/2.34.2、Accept-Encoding: gzip, deflate, br, zstd、Accept: */*、Connection: keep-alive
    curl User-Agent: curl/8.23.0,不带 Accept-Encoding
  • 每个头的实际含义(左边是名字,右边是「服务端能拿它做什么」):

    • User-Agent:客户端自报家门,也是反爬的第一道判断依据,见下面「伪装请求头」。
    • Accept:告诉服务端你能处理哪些类型,浏览器一般是 text/html,application/xhtml+xml,...。
    • Accept-Encoding:声明了你解压哪些压缩。requests 声明了 gzip 并自己解压;urllib 声明 identity(不压缩),所以它拿到的是未压缩正文。
    • Accept-Language:语言偏好,中英站点会据此返回不同文案。
    • Connection:keep-alive 复用连接(HTTP/1.1 默认),close 一次一连接。
    • Referer:从哪个页面跳过来,防盗链就是校验它。实测靶站 /img/1.png:不带 Referer 返回 403,带 Referer: http://127.0.0.1:8010/list 返回 200。
    • Cookie:登录态载体,格式是 名字=值; 名字=值(分号加空格),细节见《爬虫-代理》。
    • If-Modified-Since / If-None-Match:缓存协商,服务端没变就回 304,正文为空。
    • X-Requested-With: XMLHttpRequest:ajax 标记,很多站点用它区分「浏览器直接访问」和「程序访问」。

HTTP 响应长什么样

  • 状态行只有三段:HTTP/1.1 200 OK —— 版本、状态码、原因短语。原因短语是给人看的,程序只认数字。

HTTP 响应模型

HTTP 响应报文

  • 状态码五段分类:

    分类 含义 爬虫里最常见的
    1xx 信息,继续操作 101(协议升级,WebSocket 握手就是这个)
    2xx 成功 200、201(POST 创建成功)、206(断点续传的分片)
    3xx 重定向 301、302、304(缓存没变,正文为空)
    4xx 客户端问题 403(防盗链/风控)、404、405、429(请求太频繁)
    5xx 服务端问题 500、502/504(上游炸了)、503(过载,常配 Retry-After)
  • 靶站 /status/<code> 可以返回任意状态码,实测三种「没有正文」和「数字随便填」的情况:

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

    for code in [200, 204, 304, 404, 503, 999]:
    try:
    with urllib.request.urlopen("http://127.0.0.1:8010/status/%d" % code, timeout=10) as r:
    print(code, "->", r.status, len(r.read()), "字节")
    except Exception as e:
    print(code, "->", e)
    1
    2
    3
    4
    5
    6
    200 -> 200 356 字节
    204 -> 204 0 字节
    304 -> 304 0 字节
    404 -> HTTP Error 404: Not Found
    503 -> HTTP Error 503: Service Unavailable
    999 -> 999 356 字节
    • 4xx/5xx 在 urllib 里是异常,不是「返回一个状态码为 404 的对象」;要拿错误页正文得在 except HTTPError 里 e.read(),实测能读到 356 字节。
    • 204 与 304 按协议不允许有正文,实测都是 0 字节。
    • 999 这种非标准码也能收到(协议没禁止服务器乱填),但浏览器和代理未必老实转发,业务里表达自定义错误请用 4xx/5xx 段内的码。

常见响应头

  • 上面那次裸 socket 请求已经给出了一组真实的响应头,逐条对应:
    • Server:服务端软件与版本,实测 SpiderTarget/1.0 Python/3.14.10。
    • Date:GMT 时间,判断缓存有效期要用它而不是本地时间。
    • Content-Type:决定你怎么解码,实测 text/html; charset=utf-8。取字符集用 r.headers.get_content_charset()。
    • Content-Length:正文字节数。分块传输时它不出现。
    • Location:3xx 时告诉你去哪,实测 302 配 Location: /detail/1。
    • Allow:405/OPTIONS 时告诉你支持哪些方法,实测 OPTIONS 返回 Allow: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS。
    • Set-Cookie:给你发 cookie,实测登录页发的是 sid=xxxxxxxx; Path=/; SameSite=Lax。
    • Content-Encoding:正文被什么压缩了,见下面那个坑。
    • Transfer-Encoding: chunked:分块传输,没有 Content-Length。
    • Cache-Control / Expires / Refresh:缓存与定时跳转。

两个必须知道的坑

  • 压缩:服务端不管你有没有声明都发了 gzip 时,urllib 不会帮你解压。实测 /gzip:

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

    r = urllib.request.urlopen("http://127.0.0.1:8010/gzip", timeout=10)
    raw = r.read()
    print(raw[:4], len(raw))
    print(r.headers.get("Content-Encoding"))
    import gzip
    print(gzip.decompress(raw)[:20])
    1
    2
    3
    b'\x1f\x8b\x08\x00' 63
    gzip
    b'\xe8\xbf\x99\xe6\x98\xaf gzip \xe5\x8e\x8b\xe7\xbc\xa9\xe5\x90\x8e\xe7\x9a\x84'
    • 前两个字节 1f 8b 是 gzip 的魔数,读到这两个字节就说明要自己解压。requests 会看 Content-Encoding 自动解压,这是它比 urllib 省心的一处。
  • 分块:Transfer-Encoding: chunked 时正文是一段一段来的,http.client 与 requests 都会替你拼好,实测拿到的是四块合并后的完整内容:

    chunked.py
    1
    2
    3
    4
    5
    6
    7
    import http.client

    c = http.client.HTTPConnection("127.0.0.1", 8010, timeout=10)
    c.request("GET", "/chunked")
    r = c.getresponse()
    print(r.getheader("Transfer-Encoding"), "|", r.read())
    c.close()
    1
    chunked | b'\xe7\xac\xac 0 \xe5\x9d\x97\n\xe7\xac\xac 1 \xe5\x9d\x97\n...'
    • 只有在你自己写 socket 时才需要按 长度\r\n数据\r\n 手工切块,用标准库和 requests 都不用。

重定向

  • urlopen 默认自动跟随 3xx,跟随之后要看「最终 URL」而不是你以为的那个:

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

    with urllib.request.urlopen("http://127.0.0.1:8010/redirect", timeout=10) as r:
    print(r.status, r.geturl())


    class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
    return None # 返回 None 就不跟了


    opener = urllib.request.build_opener(NoRedirect)
    try:
    opener.open("http://127.0.0.1:8010/redirect", timeout=10)
    except HTTPError as e:
    print(e.code, e.headers.get("Location"))
    1
    2
    200 http://127.0.0.1:8010/detail/1
    302 /detail/1
  • 跟不到头时会怎样:实测靶站 /redirect-loop(302 指向自己),urlopen 连续跟了 5 次后抛异常,不是无限挂住:

    redirect_loop.py
    1
    2
    3
    4
    5
    6
    7
    import urllib.request
    from urllib.error import HTTPError

    try:
    urllib.request.urlopen("http://127.0.0.1:8010/redirect-loop", timeout=10)
    except HTTPError as e:
    print("%s: %s" % (type(e).__name__, e))
    1
    2
    3
    HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
    The last 30x error message was:
    Found
    • 底层库 http.client 完全不跟随,同一个地址它直接给你 302 和 Location 头。所以「跟不跟 3xx」取决于你用哪一层:urlopen/requests 跟,http.client 不跟。
  • 三个码的分工:301 永久(浏览器会缓存,爬虫应当更新自己存的 URL)、302 临时(历史上方法可能变)、307 临时且必须保持原方法(POST 还是 POST)。

  • 一个常见现象:http://example.com 会 301 到 https://example.com/,所以 geturl() 拿到的协议可能与传入的不同。写「同一页面去重」时要用最终 URL,不然会重复抓。

  • 304 不是重定向:它是「你缓存的还在用」,正文为空。带 If-None-Match/If-Modified-Since 时命中缓存才可能收到,实测靶站直接 /status/304 返回 0 字节正文。

HTTPS 与证书

  • 老教材里那六步(客户端拿公钥加密「会话密钥」再发给服务器)描述的是 RSA 密钥交换,现在基本看不到了。实测本机访问 https://www.example.com/ 协商到的是:

    tls_negotiation.py
    1
    2
    3
    4
    5
    6
    7
    8
    import socket
    import ssl

    ctx = ssl.create_default_context()
    with ctx.wrap_socket(socket.create_connection(("www.example.com", 443), timeout=10),
    server_hostname="www.example.com") as s:
    print("协议:", s.version())
    print("套件:", s.cipher()[0])
    1
    2
    协议: TLSv1.3
    套件: TLS_AES_256_GCM_SHA384
    • TLS 1.3 的握手是 1-RTT(第一个包里就带上密钥share),并且前向安全的 (EC)DHE 取代了「用公钥加密会话密钥」这一步;只有回退到 TLS 1.2 才走 RSA 那套。
    • 所以「HTTPS = SSL 加密等级协商 + 公钥加密会话密钥」这句话要改成:用证书确认对方身份,用 (EC)DHE 协商出对称密钥,之后正文用对称密钥加密。

HTTPS 握手

HTTPS 工作流程

  • 证书里能读到什么,实测(对本地自签服务与真实站点各取一次):

    cert.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import socket
    import ssl

    ctx = ssl.create_default_context()
    s = ctx.wrap_socket(socket.create_connection(("www.example.com", 443), timeout=10),
    server_hostname="www.example.com")
    pe = s.getpeercert()
    print("subject:", dict(x[0] for x in pe["subject"]))
    print("issuer :", dict(x[0] for x in pe["issuer"]))
    print("SAN :", pe["subjectAltName"])
    print("notAfter:", pe["notAfter"], "| 协议:", s.version())
    s.close()
    1
    2
    3
    4
    subject: {'commonName': 'example.com'}
    issuer : {'countryName': 'US', 'organizationName': 'SSL Corporation', 'commonName': 'Cloudflare TLS Issuing ECC CA 3'}
    SAN : (('DNS', 'example.com'), ('DNS', '*.example.com'))
    notAfter: Dec 25 22:56:35 2026 GMT | 协议: TLSv1.3
    • commonName 现在只算「给人看的名字」,主机名校验看的是 SAN(DNS: / IP Address: 列表)。自签那张证书的 SAN 是 ('DNS', 'localhost'), ('IP Address', '127.0.0.1'),所以按 localhost 和 127.0.0.1 都能过。
    • urlopen 返回的响应对象没有 getpeercert(),实测 AttributeError: 'HTTPResponse' object has no attribute 'getpeercert'。要看证书得自己用 ssl 包一层。

四种校验结果,全部实测

  • 在 WSL 里用 openssl 签了一张自签证书起了 https://127.0.0.1:8443,然后从 Windows 侧连:

    verify.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    import ssl
    import urllib.request

    URL = "https://127.0.0.1:8443/"
    CERT = "selfcert.pem"


    def try_open(label, ctx):
    try:
    with urllib.request.urlopen(URL, timeout=10, context=ctx) as r:
    print(label, "->", r.status, r.read().decode().strip())
    except Exception as e:
    print(label, "->", type(e).__name__, str(e)[:80])


    try_open("默认", ssl.create_default_context())
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    try_open("关掉校验", ctx)
    try_open("cafile=自签证书", ssl.create_default_context(cafile=CERT))
    1
    2
    3
    4
    默认 -> URLError <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
    self-signed certificate (_ssl.c:1085)>
    关掉校验 -> 200 self-signed ok
    cafile=自签证书 -> 200 self-signed ok
    • 正确顺序是:先 cafile / ssl_ca_certs 把对方证书加进信任链,实在不行再考虑关校验。
    • ssl._create_unverified_context() 实测也能通,但它是给内部测试用的快捷方式,别写进要跑生产环境的脚本。
  • 域名/IP 不匹配是另一类错误,实测拿只签了 localhost 的证书去校验 10.0.0.1:

    ip_mismatch.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import socket
    import ssl

    ctx0 = ssl._create_unverified_context()
    with ctx0.wrap_socket(socket.create_connection(("127.0.0.1", 8443), timeout=10),
    server_hostname="localhost") as s:
    pem = ssl.DER_cert_to_PEM_cert(s.getpeercert(binary_form=True))
    ctx = ssl.create_default_context(cadata=pem)
    try:
    ctx.wrap_socket(socket.create_connection(("127.0.0.1", 8443), timeout=10),
    server_hostname="10.0.0.1")
    except ssl.SSLCertVerificationError as e:
    print(type(e).__name__, str(e))
    1
    SSLCertVerificationError [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for '10.0.0.1'. (_ssl.c:1085)
  • requests 对应三种写法,实测:

    requests_verify.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import requests

    URL = "https://127.0.0.1:8443/"
    try:
    requests.get(URL, timeout=10)
    except Exception as e:
    print(type(e).__name__, str(e)[:90])
    print("verify=cafile ->", requests.get(URL, verify="selfcert.pem", timeout=10).status_code)
    print("verify=False ->", requests.get(URL, verify=False, timeout=10).status_code)
    1
    2
    3
    4
    SSLError HTTPSConnectionPool(host='127.0.0.1', port=8443): Max retries exceeded with url: /
    (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CE
    verify=cafile -> 200
    verify=False -> 200 # 同时抛 InsecureRequestWarning
    • verify=False 一定会伴随 InsecureRequestWarning,看到这个警告就该想想是不是该换成 verify=<ca 路径>。
    • requests 用的根证书来自 certifi 这个包,实测路径是环境里的 site-packages/certifi/cacert.pem,不是操作系统的证书库。系统装了新根证书而 certifi 没更新时,会出现「浏览器能开、程序报证书错」。

抓包:看见自己发的东西

  • 一个页面往往不止一次请求,图片、CSS、JS、接口各是一次。要判断「数据从哪个请求来」,先学会看请求列表。

  • Chrome DevTools(最常用,无需装东西):

    1. F12 → Network → 勾选 Preserve log(跨页跳转会丢记录);
    2. 过滤器选 Fetch/XHR 只看接口,Doc 看 HTML;
    3. 点某条请求看右侧:Request Headers(你发了什么)、Payload(GET 是 Query String Parameters,POST 是 Form Data)、Response / Preview(回来的内容,JSON 会被格式化);
    4. 右键请求 → Copy → Copy as cURL,可以直接粘进终端复现,也能对照出你缺了哪个头。
  • mitmproxy(可编程,实测 12.3.1):它是个中间人代理,能把「看到的请求和响应」写成日志。起服务:

    1
    mitmdump -p 8020 -s dump_flows.py
    dump_flows.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import json
    import os

    LOG = open("mitm_flows.log", "a", encoding="utf-8")


    def response(flow):
    LOG.write(json.dumps({
    "method": flow.request.method,
    "url": flow.request.pretty_url,
    "status": flow.response.status_code,
    "body_head": (flow.response.get_text(strict=False) or "")[:70],
    }, ensure_ascii=False) + "\n")
    via_mitm.py
    1
    2
    3
    4
    5
    import requests

    px = {"http": "http://127.0.0.1:8020", "https": "http://127.0.0.1:8020"}
    print(requests.get("http://127.0.0.1:8010/whoami", proxies=px, timeout=10).status_code)
    print(requests.get("https://www.example.com/", proxies=px, timeout=15).status_code)

    实测代理侧记录到的 flow(节选两条,HTTPS 那条的正文也拿到了):

    1
    2
    {"method": "GET", "url": "http://127.0.0.1:8010/whoami", "status": 200, "body_head": "{   \"method\": \"GET\",   \"path\": \"/whoami\", ..."}
    {"method": "GET", "url": "https://www.example.com/", "status": 200, "body_head": "<!doctype html><html lang=en>..."}
    • 但第二条只有在客户端信任 mitmproxy 的根证书时才成立。不信任时实测:

      1
      SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

      信任之后(verify=~/.mitmproxy/mitmproxy-ca-cert.pem)实测 200,而且客户端看到的证书签发者被换掉了:

      1
      2
      走 mitmproxy: subject {'commonName': 'example.com'}  issuer {'commonName': 'mitmproxy'}
      直连不进代理: subject {'commonName': 'example.com'} issuer {'commonName': 'Cloudflare TLS Issuing ECC CA 3'}
    • 这就是「HTTPS 只是链路加密」的意思:它防不了你主动配置的中间人。反过来,App 与严格校验证书(证书锁定/certificate pinning)的站点,普通抓包工具拿不到明文。

  • Fiddler:Windows 上老牌图形化抓包,Telerik 维护,Classic 版免费;要抓 HTTPS 得在 Tools → Options → HTTPS 勾 Capture HTTPS Traffic + Decrypt HTTPS traffic 并信任它生成的根证书,本质与上面 mitmproxy 装 CA 是同一件事。注意它只是一个系统代理,程序不走系统代理(requests 默认就不走)时抓不到,需要显式配 proxies。

  • 不想装任何工具时,最省事的「看自己发了什么」是让服务端回显:靶站的 /whoami 直接返回收到的全部请求头,实测能一眼看出 UA、Accept-Encoding、Connection 的差异。

urllib 五个子模块

子模块 干什么 爬虫里常用程度
urllib.request 发请求、收响应、处理重定向与代理 主力
urllib.parse 拆 URL、拼 URL、编解码查询串 主力
urllib.error HTTPError / URLError / ContentTooShortError 异常分支
urllib.response urlretrieve 用的辅助类型,一般不直接 import 基本不碰
urllib.robotparser 读 robots.txt 合规检查

Request 对象的四个细节

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

req = urllib.request.Request("http://127.0.0.1:8010/whoami")
print(req.get_method())
print(urllib.request.Request("http://127.0.0.1:8010/x", data=b"a=1").get_method())
print(urllib.request.Request("http://127.0.0.1:8010/x", data=b"a=1", method="PUT").get_method())
print(req.get_header("User-agent"))
req.add_header("User-Agent", "Mozilla/5.0 Chrome/156.0")
print(req.get_header("User-agent"), "|", req.get_header("USER-AGENT"))
print(req.headers)
1
2
3
4
5
6
GET
POST
PUT
None
Mozilla/5.0 Chrome/156.0 | None
{'User-agent': 'Mozilla/5.0 Chrome/156.0'}
  • 没有 req.method 这个属性,实测直接取会 AttributeError: 'Request' object has no attribute 'method',要读用 get_method()。
  • 传了 data 方法自动变 POST,想改回来用 method="PUT" 这类显式参数。
  • Request 内部把头名规范化成「首字母大写、其余小写」(User-agent),而 get_header() 是大小写敏感的:实测 get_header("USER-AGENT") 返回 None。
  • 默认 UA 不在 Request 上,是发送时由 opener 补的 Python-urllib/3.14。

parse:编码与解码

parse_all.py
1
2
3
4
5
6
7
8
9
10
11
12
13
from urllib.parse import quote, quote_plus, unquote_plus, urlencode, parse_qs, parse_qsl

s = "测试/abc 123&="
print(quote(s))
print(quote(s, safe=""))
print(quote_plus(s))
print(unquote_plus(quote_plus(s)))
print(urlencode({"name": "张三", "age": 25}))
print(urlencode([("name", "张三"), ("name", "李四")]))
print(urlencode({"name": ["张三", "李四"], "age": 25}, doseq=True))
print(urlencode({"a": {"b": 1}}))
print(parse_qs("name=张三&age=25&name=李四&empty"))
print(parse_qsl("name=张三&age=25&name=李四"))
1
2
3
4
5
6
7
8
9
10
%E6%B5%8B%E8%AF%95/abc%20123%26%3D
%E6%B5%8B%E8%AF%95%2Fabc%20123%26%3D
%E6%B5%8B%E8%AF%95%2Fabc+123%26%3D
测试/abc 123&=
name=%E5%BC%A0%E4%B8%89&age=25
name=%E5%BC%A0%E4%B8%89&name=%E6%9D%8E%E5%9B%9B
name=%E5%BC%A0%E4%B8%89&name=%E6%9D%8E%E5%9B%9B&age=25
a=%7B%27b%27%3A+1%7D
{'name': ['张三', '李四'], 'age': ['25']}
[('name', '张三'), ('age', '25'), ('name', '李四')]
  • quote 默认不编码 /(safe="/"),quote_plus 编码 / 且把空格变成 +;查询串用 urlencode,路径段用 quote。

  • urlencode 遇到嵌套字典不报错,实测得到 a=%7B%27b%27%3A+1%7D(把 Python 字典 str() 之后再编码),服务端拿到的是一串 {'b': 1} 的文本。要传结构就自己 json.dumps 后显式编码。

  • parse_qs 的值永远是列表(同名参数会出现多次),parse_qsl 保留顺序;空值参数默认被丢掉,要留就传 keep_blank_values=True(实测 {'a': [''], 'b': ['1']})。

  • URL 里直接写中文会炸,实测:

    unicode_url.py
    1
    2
    3
    4
    5
    6
    import urllib.request

    try:
    urllib.request.urlopen("http://127.0.0.1:8010/search?q=三国", timeout=10)
    except UnicodeEncodeError as e:
    print(type(e).__name__ + ":", e)
    1
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)

    先 urlencode 再发,实测得到 http://127.0.0.1:8010/search?q=%E4%B8%89%E5%9B%BD 并正常返回 200。

error:两类异常

  • 继承关系实测 issubclass(HTTPError, URLError) 为 True,所以 except URLError 会连 HTTPError 一起接住,要分开写就先写 HTTPError。

  • 三种失败的原文:

    three_failures.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import urllib.request
    from urllib.error import HTTPError, URLError

    try:
    urllib.request.urlopen("http://127.0.0.1:8010/status/404", timeout=10)
    except HTTPError as e:
    print("404 -> HTTPError: %s(e.read() 还能读到 %d 字节错误页正文)"
    % (e, len(e.read())))
    try:
    urllib.request.urlopen("http://127.0.0.1:1/", timeout=10)
    except URLError as e:
    print("端口没人听 -> URLError,e.reason 是 %s %s" % (type(e.reason).__name__, e.reason))
    try:
    urllib.request.urlopen("http://nonexistent-domain.invalid/", timeout=10)
    except URLError as e:
    print("域名解析不了 -> URLError,e.reason 是 %s %s" % (type(e.reason).__name__, e.reason))
    1
    2
    3
    404          -> HTTPError: HTTP Error 404: Not Found(e.read() 还能读到 356 字节错误页正文)
    端口没人听 -> URLError,e.reason 是 ConnectionRefusedError [WinError 10061] 由于目标计算机积极拒绝,无法连接。
    域名解析不了 -> URLError,e.reason 是 gaierror [Errno 11001] getaddrinfo failed
  • 超时有两种形态,容易搞混,实测:

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

    try:
    urllib.request.urlopen("http://127.0.0.1:8010/slow?ms=2000", timeout=0.5)
    except Exception as e:
    print("/slow?ms=2000 且 timeout=0.5 -> %s: %s (直接抛,不包 URLError)"
    % (type(e).__name__, e))
    try:
    urllib.request.urlopen("http://10.255.255.1/", timeout=2)
    except Exception as e:
    print("10.255.255.1 且 timeout=2 -> %s: %s" % (type(e).__name__, e))
    1
    2
    /slow?ms=2000 且 timeout=0.5 -> TimeoutError: timed out        (直接抛,不包 URLError)
    10.255.255.1 且 timeout=2 -> URLError: <urlopen error timed out>
    • 结论:except 时把 TimeoutError 也带上,或者统一 except (urllib.error.URLError, TimeoutError)。
  • ContentTooShortError 只在 urlretrieve 下载不完整时抛(urllib.error 里确实有它)。

Response 对象

response_attrs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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"}
r = urllib.request.urlopen(urllib.request.Request("https://ssr1.scrape.center/page/1",
headers=HEADERS), timeout=20)
print(type(r).__name__, "| version:", r.version, "| status:", r.status, r.reason)
print(r.geturl(), "| getcode():", r.getcode())
print(type(r.headers).__name__, "| info() 是同一个对象:", r.info() is r.headers)
print("charset:", r.headers.get_content_charset())
print("get_all('Set-Cookie'):", r.headers.get_all("Set-Cookie"))
first = r.read()
print("第一次 read:", len(first), "字节 | 第二次:", len(r.read()), "字节")
print("r.fp:", type(r.fp).__name__)
api = json.loads(urllib.request.urlopen("https://spa1.scrape.center/api/movie?limit=2&offset=0", timeout=20).read())
print(api["count"], [x["name"] for x in api["results"]])
1
2
3
4
5
6
7
8
HTTPResponse | version: 11 | status: 200 OK
https://ssr1.scrape.center/page/1 | getcode(): 200
HTTPMessage | info() 是同一个对象: True
charset: utf-8
get_all('Set-Cookie'): None
第一次 read: 41667 字节 | 第二次: 0 字节
r.fp: NoneType
104 ['霸王别姬', '这个杀手不太冷']
  • version 是整数 11(代表 HTTP/1.1),不是字符串。
  • 正文只能读一次,第二次是 0 字节;要复用先存进变量。
  • read(100) 只保证「最多 100 字节」,readlines() 在 HTTP 上是把整个响应读进内存再切行,大文件别用。
  • r.fp 在 urlopen 这条路径上是 NoneType,老教程说的「拿原始 socket」在这里不适用,要原始 socket 请用 http.client。
  • 多值头(Set-Cookie 这种)用 headers.get_all()。另外 urlopen 每次都是独立请求,不会保存也不会回带 cookie:实测登录页发了 Set-Cookie: sid=...,紧接着再请求 /readcookie 拿到的仍是 {"cookie": "", "sid": ""}。要维持登录态得配 HTTPCookieProcessor,完整写法见《爬虫-代理》。
  • 解码:r.headers.get_content_charset() 拿到 utf-8 再 decode。实测对 bytes 直接 str(raw) 会得到 b'<!doctype html>...' 这种带转义的字符串,是新手最常犯的一类错。

urlretrieve 与分块下载

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

path, msg = urllib.request.urlretrieve("http://127.0.0.1:8010/video", "dl.bin")
print(os.path.getsize("dl.bin"), "字节 |", sorted(msg.keys()))

r = urllib.request.urlopen("http://127.0.0.1:8010/video", timeout=10)
total = 0
with open("dl2.bin", "wb") as f:
while True:
chunk = r.read(64 * 1024)
if not chunk:
break
f.write(chunk)
total += len(chunk)
print("分块累计:", total, "字节")
1
2
1048576 字节 | ['Content-Length', 'Content-Type', 'Date', 'Server']
分块累计: 1048576 字节
  • urlretrieve 返回 (本地路径, 响应头),一次进内存再落盘;文件大就用上面 read(64K) 的循环。
  • 断点续传靠 Range: bytes=0-1023 请求头 + 服务端 206 Partial Content,靶站没实现 Range,这条只作方向提示。

两个最小可用的例子

  • GET:urllib 抓服务端渲染页,参数直接写在查询串里,中文才需要 urlencode。

    get_list.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import re
    import urllib.parse
    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"}
    url = "https://ssr1.scrape.center/page/2"
    req = urllib.request.Request(url, headers=HEADERS)
    with urllib.request.urlopen(req, timeout=20) as r:
    html = r.read().decode("utf-8")
    print(r.getcode(), r.geturl())
    print("正文", len(html), "字符,卡片", html.count('class="el-card item'), "张")
    print(re.findall(r'class="name">\s*<h2[^>]*>(.*?)</h2>', html, re.S)[:2])
    print(urllib.parse.urlencode({"limit": 3, "offset": 10, "name": "三国"}))
    1
    2
    3
    4
    200 https://ssr1.scrape.center/page/2
    正文 41669 字符,卡片 10 张
    ['V字仇杀队 - V for Vendetta', '少年派的奇幻漂流 - Life of Pi']
    limit=3&offset=10&name=%E4%B8%89%E5%9B%BD
    • 这个站的分页是「路径型」/page/2,不带尾斜杠:/page/2/ 实测 404。
    • JSON 接口那边参数名写错不会有提示:spa1.scrape.center/api/movie 只认 limit/offset,多给的 name=三国 被忽略,返回的仍是 offset 位置上的 3 条(详见《爬虫-JSONPath》)。
  • POST:data 必须是 bytes,表单先 urlencode 再 encode。这条留在靶站:在线练习站不收表单,「服务端拒绝」的 403 分支要每次都能跑出来,只能自己搭一个校验隐藏字口的端点。靶站的 /submit 会校验一个隐藏字段 token:

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

    def post(token):
    data = urllib.parse.urlencode({"name": "lilei", "token": token}).encode()
    req = urllib.request.Request("http://127.0.0.1:8010/submit", data=data)
    try:
    with urllib.request.urlopen(req, timeout=10) as r:
    return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
    return e.code, json.loads(e.read())

    print(post("wrong"))
    print(post("tok-8f2c"))
    1
    2
    403 {'ok': False, 'why': 'token 不对', 'got': {'name': 'lilei', 'token': 'wrong'}}
    200 {'ok': True, 'kind': 'form', 'data': {'name': 'lilei', 'token': 'tok-8f2c'}}
    • 注意 Content-Type 是 application/x-www-form-urlencoded(urllib 带 data 时默认就是这个),发 JSON 要自己改头:headers={"Content-Type": "application/json"} + data=json.dumps(obj).encode()。
  • 需要登录态、验证码、cookie 的写法不在这里展开,见《爬虫-代理》的 cookie 登录一节;requests 版本见《爬虫-Requests》。

伪装请求头

  • 这是反爬的第一道,也是最容易验证的一道。靶站 /ua 只判断 UA 里有没有 Mozilla:

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

    def probe(headers=None):
    req = urllib.request.Request("http://127.0.0.1:8010/ua", headers=headers or {})
    try:
    with urllib.request.urlopen(req, timeout=10) as r:
    return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
    return e.code, json.loads(e.read())

    print(probe())
    print(probe({"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/156.0"}))
    1
    2
    403 {'ok': False, 'ua': 'Python-urllib/3.14', '判定': '非浏览器 UA,拒绝'}
    200 {'ok': True, 'ua': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/156.0', '判定': '放行'}
  • UA 从哪来最靠谱:从你自己浏览器里抄。DevTools 任意请求的 Request Headers 里就有整串,实测本机 Chrome 无头模式给出的是:

    chrome_ua.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import json
    import re
    import subprocess

    CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    dom = subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--dump-dom",
    "http://127.0.0.1:8010/whoami"],
    capture_output=True, text=True, encoding="utf-8", timeout=60).stdout
    headers = json.loads(re.search(r"<pre>(.*)</pre>", dom, re.S).group(1))["headers"]
    print(headers["User-Agent"])
    1
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/156.0.0.0 Safari/537.36
    • 注意 HeadlessChrome 这个词:无头浏览器的 UA 自带标记,很多反爬就查这个字符串(selenium 的其它破绽见《爬虫-Selenium和PhantomJS》)。
  • fake-useragent 2.2.0 实测:包体里带本地数据(data/browsers.jsonl),不联网也能出结果,但 ua.random 给的是相当旧的 iPhone UA:

    fake_ua.py
    1
    2
    3
    4
    5
    6
    import random

    from fake_useragent import UserAgent

    random.seed(6)
    print(UserAgent().random)
    1
    Mozilla/5.0 (iPhone; CPU iPhone OS 18_3_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) GSA/363.0.743255906 Mobile/15E148 Safari/604.1
    • 想按浏览器取时它还会先去联网拉最新数据,拉不到会打印一行 Error occurred during getting browser(s): ... but was suppressed with fallback. 再退回本地数据。
    • 结论:这个库适合「随机换个样子」,不适合「伪装成当前主流桌面浏览器」。真要像,就固定一条从自己浏览器抄来的 UA。
  • 只改 UA 是不够的。真实浏览器是一整套头一起出现的:实测无头 Chrome 访问 /whoami 时发了 14 个头,urllib 只发 4 个。

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

    CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    dom = subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--dump-dom",
    "http://127.0.0.1:8010/whoami"],
    capture_output=True, text=True, encoding="utf-8", timeout=60).stdout
    chrome_headers = json.loads(re.search(r"<pre>(.*)</pre>", dom, re.S).group(1))["headers"]
    with urllib.request.urlopen("http://127.0.0.1:8010/whoami", timeout=10) as r:
    urllib_headers = json.loads(r.read())["headers"]
    print("无头 Chrome 发了 %d 个头" % len(chrome_headers))
    print("urllib 发了 %d 个头:%s" % (len(urllib_headers), "、".join(urllib_headers)))
    1
    2
    无头 Chrome 发了 14 个头
    urllib 发了 4 个头:Accept-Encoding、Host、User-Agent、Connection
    1
    2
    3
    4
    Host、Connection: keep-alive、sec-ch-ua、sec-ch-ua-mobile、sec-ch-ua-platform、
    Upgrade-Insecure-Requests: 1、User-Agent、Accept(带 image/jxl、image/avif 等一长串)、
    Sec-Fetch-Site / Mode / User / Dest、Accept-Encoding: gzip, deflate, br, zstd、
    Accept-Language: zh-CN,zh;q=0.9

    头越少越像脚本,尤其缺 Sec-Fetch-* 与 sec-ch-ua 这一组,是现在最容易暴露的地方。这也是为什么后面要用 requests.Session(《爬虫-Requests》)或干脆上浏览器方案(《爬虫-Selenium和PhantomJS》)。

参考

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