步骤 | 操作 | 目的 |
---|---|---|
1️⃣ | 分析目标网页结构 | 使用浏览器开发者工具(F12)查看网络请求、HTML 结构 |
2️⃣ | 构造请求头信息(headers) | 设置 User-Agent、Referer、Cookie 等字段,模拟浏览器行为 |
3️⃣ | 发送 HTTP 请求 | GET / POST 方法选择,构造参数(params / data) |
4️⃣ | 接收响应内容(response) | 获取 HTML / JSON / 图片等资源 |
5️⃣ | 解析响应内容 | 使用 BeautifulSoup、json、lxml 等解析数据 |
6️⃣ | 存储或处理数据 | 写入文件、数据库或进行可视化分析 |
import requests
from fake_useragent import UserAgent
url = "https://p1.music.126.net/W49WgaduTlqsGdb2H7qV7g==/109951171136346838.jpg?imageView&quality=89"
headers = {"User-Agent": UserAgent().random}
response = requests.get(url, headers=headers)
with open("网易云爬取.jpg", "wb") as f:
f.write(response.content)
✅ 说明:使用
requests.get()
获取二进制数据,并以wb
模式保存为图片文件。
url = "https://m804.music.126.net/.../57706dc05dee50ae43519481cf4aa678.m4a"
headers = {"User-Agent": UserAgent().random}
response = requests.get(url, headers=headers)
with open("网易云.mp3", "wb") as f:
f.write(response.content)
⚠️ 注意:部分音乐平台对链接设置了防盗链,可能需要添加 Referer 或 Cookie 才能访问。
url = "https://vodkgeyttp8.vod.126.net/cloudmusic/c15f/core/...mp4?wsSecret=..."
headers = {"User-Agent": UserAgent().random}
response = requests.get(url, headers=headers)
with open("网易云.mp4", "wb") as mv:
mv.write(response.content)
提示:大文件建议分块下载(使用
stream=True
),避免内存占用过高。
url = "https://tieba.baidu.com/f?"
headers = {
"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 ..."
}
params = {
"kw": "蔡徐坤",
"ie": "utf-8"
}
response = requests.get(url, headers=headers, params=params)
with open("蔡徐坤.html", "wb") as f:
f.write(response.content)
https://tieba.baidu.com/f?kw=%E8%94%A1%E5%BE%90%E5%9D%A4&ie=utf-8
https://tieba.baidu.com/f?kw=%E8%94%A1%E5%BE%90%E5%9D%A4&ie=utf-8&pn=50
规律总结:
pn
表示页码偏移量pn=0
,第二页 pn=50
,第三页 pn=100
...for i in range(pages):
params = {
"kw": word,
"ie": "utf-8",
"pn": i * 50
}
res = requests.get(url, headers=headers, params=params)
with open(f"{word}{i+1}.html", "wb") as f:
f.write(res.content)
✅ 规律总结:
pn
控制翻页:第一页 pn=0
,第二页 pn=50
,以此类推class TieBaInfoGet:
def __init__(self):
self.url = "https://tieba.baidu.com/f?"
self.headers = {"User-Agent": "..."}
def get(self, params):
return requests.get(self.url, headers=self.headers, params=params).content
def save(self, filename, content):
with open(f"{filename}.html", "wb") as f:
f.write(content)
def run(self):
word = input("请输入贴吧名称:")
pages = int(input("请输入要爬取的页数:"))
for page in range(pages):
params = {"kw": word, "ie": "utf-8", "pn": page * 50}
data = self.get(params)
self.save(f"{word}_{page+1}", data)
✅ 优点:代码结构清晰、易于维护和扩展。
特性 | GET | POST |
---|---|---|
参数位置 | URL 中(查询字符串) | 请求体中 |
安全性 | 不安全(暴露参数) | 相对更安全 |
数据长度限制 | 有限(URL 长度限制) | 几乎无上限 |
用途 | 获取数据 | 提交数据(如登录、注册) |
url = "https://ifanyi.iciba.com/index.php?c=trans"
data = {
"from": "auto",
"to": "auto",
"q": input("请输入要翻译的内容:")
}
headers = {"User-Agent": "Mozilla/5.0 ..."}
res = requests.post(url, data=data, headers=headers)
result = json.loads(res.text)
print(result['out'])
✅ 说明:使用
requests.post(data=...)
提交表单数据,返回 JSON 格式结果。
url = "https://www.bilibili.com/"
headers = {
"User-Agent": "...",
"Cookie": "你的完整 Cookie 字符串"
}
res = requests.get(url, headers=headers)
print(res.text)
⚠️ 缺点:Cookie 有时效性,容易过期,且手动复制易出错。
session = requests.Session()
session.post(login_url, data=login_data)
res = session.get(protected_url)
✅ 优势:
- 自动保存 Cookie
- 自动携带到后续请求中
- 更适合模拟登录流程
1. Cookie 的核心作用
典型应用场景:
2. Session 的核心作用
典型应用场景:
Cookie 和 Session 的主要区别
特性 | Cookie | Session |
---|---|---|
存储位置 | 客户端(浏览器) | 服务端(内存 / 数据库 / 缓存) |
安全性 | 较低,容易被篡改或窃取 | 较高,敏感数据不暴露给客户端 |
数据量限制 | 每个 Cookie 不超过 4KB,每个域名最多 20 个 Cookie | 取决于服务器配置,理论上可以存储更多数据 |
生命周期 | 可以设置过期时间(如 Max-Age 或 Expires ),也可以是会话级别的(关闭浏览器即失效) |
一般由服务器控制,可以设置较长时间的有效期 |
传输方式 | 每次请求都会自动携带 Cookie 到服务器 | 需要通过某种方式(如 Cookie 中的 Session ID)关联到 Session 数据 |
适用场景 | 存储轻量级、非敏感的数据 | 存储敏感信息、复杂结构数据,适合需要高安全性的场景 |
类型 | 特点 |
---|---|
透明代理 | 服务器知道你在用代理,也知道真实 IP |
匿名代理 | 服务器知道用了代理,但不知道真实 IP |
高匿代理 | 服务器不知道用了代理,也不知道真实 IP |
proxies = {
"http": "http://ip:port",
"https": "https://ip:port"
}
res = requests.get(url, proxies=proxies, headers=headers)
proxies = {
"http": "http://47.26.117.24:9527"
}
res = requests.get("https://www.baidu.com", proxies=proxies, headers=headers)
print(res.text)
⚠️ 注意:
- 代理 IP 可能不稳定,建议设置超时机制(
timeout=5
)- 免费代理质量较低,可考虑购买商业代理服务
proxy_pool = [
{"http": "http://ip1:port"},
{"http": "http://ip2:port"},
...
]
import random
proxies = random.choice(proxy_pool)
✅ 建议: