从零构建可落地的爬虫解决方案|详解反爬机制|解析法律边界|分享真实行业案例|持续更新高价值技术内容
在进入复杂反爬对抗前,必须夯实基础能力。很多学习者急于求成,跳过 HTTP 协议、HTML 结构、DOM 解析等核心环节,导致后期调试困难、效率低下,甚至误入歧途。本部分将系统梳理 Python 爬虫必备的三大支柱知识体系,结合真实代码示例,帮助您建立完整的认知框架。
所有网页数据都通过 HTTP(S) 协议传输。理解请求与响应的完整生命周期,是编写稳定爬虫的前提。以浏览器访问 https://www.xservx.com/article/1 为例,其过程可分解为以下关键环节:
以 requests 库为例,一个标准 GET 请求应包含必要 Headers:
import requests
url = "https://www.xservx.com/article/1"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,**", handle_request)
page.on("response", lambda resp:
print("API Response:", resp.url) if "api/news" in resp.url else None)
page.goto("https://example.com/news")
page.wait_for_timeout(3000) # 等待动态加载
browser.close()
反爬不是单一技术点,而是多维度的攻防体系。我们按常见策略分类解析应对方案,避免盲目尝试。
服务器常检查 User-Agent、Accept-Language、Referer 等字段。简单伪装示例:
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Referer": "https://www.google.com/search?q=python爬虫",
"Upgrade-Insecure-Requests": "1"
}
⚠️ 注意:不要使用常见 UA 列表中的“热门 UA”,应模拟真实用户分布(如 Mac + Safari + 中文环境)。
常见策略:同一 IP 短时请求超过阈值(如 100 次/分钟)即封禁。解决方案:
requests.Session() 减少 TCP 握手次数代理配置示例:
proxies = {
"http": "http://user:pass@proxy.example.com:8080",
"https": "http://user:pass@proxy.example.com:8080"
}
response = requests.get(url, headers=headers, proxies=proxies, timeout=10)
动态生成的 Cookie(如 __cf_bm、_gid)常用于反爬。应对方法:
示例:Selenium 登录后提取 Cookie 并用于 requests:
from selenium import webdriver
import requests
driver = webdriver.Chrome()
driver.get("https://example.com/login")
# 执行登录操作...
cookies = driver.get_cookies()
driver.quit()
session = requests.Session()
for cookie in cookies:
session.cookies.set(cookie["name"], cookie["value"], domain=cookie["domain"])
# 使用 session 发起请求
resp = session.get("https://example.com/user/profile")
高频出现于登录、搜索、分页参数(如 sign、timestamp)。破解路径:
sign、encrypt)示例:某站搜索参数 sign 由 md5(q + salt + ts) 生成
import hashlib
import time
def generate_sign(query):
salt = "python爬虫小王子"
ts = str(int(time.time()))
raw = query + salt + ts
sign = hashlib.md5(raw.encode()).hexdigest()
return sign, ts
query = "Python教程"
sign, ts = generate_sign(query)
print(f"sign={sign}&ts={ts}")
高级反爬会监测鼠标移动轨迹、滚动速度、键盘敲击等。应对策略:
mouse.move(x, y) 生成自然轨迹navigator.webdriver 标志以下案例均来自生产环境,已脱敏处理,保留核心逻辑与技巧。
目标:抓取「电脑数码」类目下所有商品的标题、价格、评价数、店铺名
难点:需登录才能查看价格;商品列表分页参数加密;价格字段通过 JS 动态渲染
解决方案:
/api/products?cat=computer&page=1&sign=xxx,逆向 sign 生成逻辑/api/product/detail?id=123核心代码片段:
# 登录后保存 Cookie
session = requests.Session()
session.cookies.update(cookies_from_selenium)
# 请求分页列表
for page in range(1, 51):
sign, ts = generate_sign(f"computer{page}")
url = f"https://api.example.com/products?cat=computer&page={page}&sign={sign}&ts={ts}"
resp = session.get(url)
products = resp.json()["data"]["list"]
for p in products:
# 请求详情页
detail_resp = session.get(f"https://api.example.com/product/detail?id={p['id']}")
detail = detail_resp.json()
print(f"{detail['title']} | ¥{detail['price']} | 评价 {detail['comments']} 条 | 店铺:{detail['shop']}")
案例二:学术论文数据库(知网/万方)的文献信息提取
目标:按关键词检索,提取题名、作者、来源、摘要、引用数
难点:反爬严格(滑块验证、IP 封禁);摘要内容通过 JS 加载;需模拟检索行为
解决方案:
- 使用代理池 + 请求间隔 5~15 秒
- 通过 DevTools 找到隐藏的 API:
/search?kw=Python爬虫&year=2020
- 对每篇论文,请求详情页:
/paper/detail?id=CJFDXXX
- 用正则提取摘要:
re.search(r'"abstract":"(.*?)"', resp.text)
数据存储:导出为 CSV + SQLite 双备份,便于后续分析。
案例三:社交媒体评论抓取(含情感分析)
目标:抓取某视频下前 1000 条评论,用于舆情分析
难点:评论分页采用游标(cursor);评论内容加密;需登录查看全部评论
突破点:
- 分析请求:
/comments?video_id=123&cursor=abc,返回加密 JSON
- 通过 JS 逆向找到解密密钥(如 XOR 0x5A)
- 用 Playwright 模拟滚动加载更多评论(每次 20 条)
- 对评论文本进行中文分词与情感极性判断(使用 SnowNLP)
爬虫技术本身无罪,但使用不当可能触犯《刑法》第285条(非法获取计算机信息系统数据罪)、《民法典》第1034条(侵犯隐私权)及《反不正当竞争法》。
https://example.com/robots.txt,禁止项(如 Disallow: /admin/)不可访问示例:某公司因爬取竞争对手商品价格用于内部定价,被认定为不正当竞争,赔偿 200 万元。
真实案例:2023 年某公司因爬取大众点评商户信息并用于自家APP,被判赔偿 30 万元并公开道歉。
X-Request-ID 便于追踪A:直接爬取登录态后的内容存在极高法律风险。微信对爬虫检测严格,且公众号内容受著作权保护。建议:
A:不建议绕过滑块验证码——这属于主动规避安全措施,可能构成违法。合规做法:
A:可以,但需注意:
A:按场景选择:
| 维度 | requests | Scrapy |
|---|---|---|
| 适用规模 | 小规模(<1000页) | 中大型(>1万页) |
| 开发复杂度 | 低 | 中 |
| 异步支持 | 需配合 asyncio | 内置 Twisted |
| 扩展性 | 需手动编码 | 插件化(中间件/管道) |
A:可采取以下措施:
X-Source: python爬虫小王子)