爬虫-基本入门
这篇讲什么
- 爬虫在技术上就两件事:用程序发 HTTP 请求拿到内容,再从内容里把想要的字段挑出来。这篇先把「HTTP 报文到底长什么样」用真实字节摊开看一遍。
- 顺手把 Python 标准库
urllib的五个子模块逐个跑一遍:request发请求、parse拆 URL、error接异常、response读响应、robotparser看站点规矩。 - 最后落到两个能直接抄走的最小例子:一个用
urllib抓在线练习站的列表页,一个带 token 的 POST 表单,并解释为什么服务端一眼就能认出你不是浏览器。
爬虫是什么
-
本篇的输出都是本机实跑的结果,数据源分两类:
- 抓内容的例子一律用公开练习站 scrape.center——《Python3 网络爬虫开发实战》作者搭的练习站,专门给爬虫练手,
ssr1子站是服务端渲染的电影列表,不用浏览器就能拿到完整 HTML。 - 协议级的例子(裸报文、状态码、gzip、重定向、cookie、表单被拒、自签证书)留在本机靶站:一个只用标准库写的小站点。在线站不会稳定地给你 500、403 和一张自签证书,这类演示只能自己搭。
- 抓内容的例子一律用公开练习站 scrape.center——《Python3 网络爬虫开发实战》作者搭的练习站,专门给爬虫练手,
-
环境基线:Python 3.14.10 + requests 2.34.2 + mitmproxy 12.3.1。
-
一句话:爬虫就是一个「不显示页面的浏览器」。浏览器做的事是「解析 URL → 建 TCP 连接 → 发 HTTP 请求 → 收响应 → 渲染」,爬虫只需要前三步加一步「从响应里取数据」。
-
三类爬虫的差别在「抓多少」和「抓多深」:
类型 目标 产物 典型做法 通用爬虫 尽可能覆盖全网 倒排索引、网页库 从种子 URL 出发顺着链接爬,先存后处理 聚焦爬虫 某一类具体数据 结构化字段(表格里的那些列) 只跟进与主题相关的链接,边爬边解析 接口爬虫 某个 JSON 接口 直接落库 找到 ajax 背后的接口,绕开 HTML -
通用爬虫怎么发现新站点,靠的是三件事:站点主动提交 URL、友情链接把链接带进图里、以及与 DNS 服务商合作拿到新注册域名。这三件事聚焦爬虫都用不上,聚焦爬虫的种子 URL 是你自己给的。
-
聚焦爬虫的三步固定不变:
- 给一个 URL;
- 写程序模拟浏览器访问它,拿到 HTML 或 JSON;
- 按规则解析,把字段取出来存好。
-
网页能被程序处理的前提有三条,也正是这三条决定了爬虫的写法:每个页面有唯一 URL、内容是 HTML(或 JSON)结构、传输走 HTTP/HTTPS。

robots.txt 是约定,不是开关
-
urllib.robotparser能读它,实测靶站的User-agent: *+Disallow: /private/:probe_robots.py 1
2
3
4
5
6
7
8
9from 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
4False
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
19import 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
6HTTP/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 通常没有)。响应同理:状态行、响应头、空行、响应体。

- 空行不是排版。服务端是靠它判断「头说完了」,实测把最后那个
\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
10import 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
8GET 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
6from 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
2ParseResult(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有值。

-
拼相对链接必须用
urljoin,手写字符串拼接是错的(实测六种):urljoin_demo.py 1
2
3
4
5from 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.urlopenAccept-Encoding: identity、Host、User-Agent: Python-urllib/3.14、Connection: closerequests.getHost、User-Agent: python-requests/2.34.2、Accept-Encoding: gzip, deflate, br, zstd、Accept: */*、Connection: keep-alivecurlUser-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—— 版本、状态码、原因短语。原因短语是给人看的,程序只认数字。


-
状态码五段分类:
分类 含义 爬虫里最常见的 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
8import 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
6200 -> 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 段内的码。
- 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
8import 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
3b'\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
7import 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都不用。
- 只有在你自己写 socket 时才需要按
重定向
-
urlopen默认自动跟随 3xx,跟随之后要看「最终 URL」而不是你以为的那个:redirect.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import 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
2200 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
7import 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
3HTTPError: 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
8import 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 协商出对称密钥,之后正文用对称密钥加密。


-
证书里能读到什么,实测(对本地自签服务与真实站点各取一次):
cert.py 1
2
3
4
5
6
7
8
9
10
11
12import 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
4subject: {'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.3commonName现在只算「给人看的名字」,主机名校验看的是 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
21import 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
13import 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
9import 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
4SSLError 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 # 同时抛 InsecureRequestWarningverify=False一定会伴随InsecureRequestWarning,看到这个警告就该想想是不是该换成verify=<ca 路径>。requests用的根证书来自certifi这个包,实测路径是环境里的site-packages/certifi/cacert.pem,不是操作系统的证书库。系统装了新根证书而certifi没更新时,会出现「浏览器能开、程序报证书错」。
抓包:看见自己发的东西
-
一个页面往往不止一次请求,图片、CSS、JS、接口各是一次。要判断「数据从哪个请求来」,先学会看请求列表。
-
Chrome DevTools(最常用,无需装东西):
- F12 → Network → 勾选
Preserve log(跨页跳转会丢记录); - 过滤器选
Fetch/XHR只看接口,Doc看 HTML; - 点某条请求看右侧:
Request Headers(你发了什么)、Payload(GET 是 Query String Parameters,POST 是 Form Data)、Response/Preview(回来的内容,JSON 会被格式化); - 右键请求 →
Copy→Copy as cURL,可以直接粘进终端复现,也能对照出你缺了哪个头。
- F12 → Network → 勾选
-
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
13import 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
5import 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 对象的四个细节
1 | import urllib.request |
1 | GET |
- 没有
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:编码与解码
1 | from urllib.parse import quote, quote_plus, unquote_plus, urlencode, parse_qs, parse_qsl |
1 | %E6%B5%8B%E8%AF%95/abc%20123%26%3D |
-
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
6import 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
16import 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
3404 -> 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
11import 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 对象
1 | import json |
1 | HTTPResponse | version: 11 | status: 200 OK |
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 与分块下载
1 | import os |
1 | 1048576 字节 | ['Content-Length', 'Content-Type', 'Date', 'Server'] |
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
14import 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
4200 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
14import 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
2403 {'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
13import 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
2403 {'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
10import 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-useragent2.2.0 实测:包体里带本地数据(data/browsers.jsonl),不联网也能出结果,但ua.random给的是相当旧的 iPhone UA:fake_ua.py 1
2
3
4
5
6import 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
14import 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、Connection1
2
3
4Host、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》)。