Files
Obsidian/MyselfDev/workBuddy/Workbuddy介绍如何抓取CSDN.md
coco 8b94d76799 a
2026-07-21 13:57:15 +08:00

251 lines
8.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
这次是分类页(category),脚本里的 API 调用加了 `category=12932874` 参数过滤,成功从 10 页
(每页 20 篇)里捞出了全部 198 篇。脚本 `csdn_scraper_cookie.py` 已经是通用的了,改三个变量就能对付任意 CSDN 用户主页或分类页。
## 整体思路
CSDN 防爬手段很多,我绕过的核心方案是 **"不走前端,直接调 API + 模拟浏览器 Headers"**。下面完整拆解:
---
## 第一步:获取文章列表
普通爬虫的做法是解析博客主页 HTML,但 CSDN 的列表页是 **JavaScript 动态渲染**的,直接 `requests.get()` 拿到的 HTML 里根本没有文章列表内容。
我用的方法是**直接调 CSDN 的内部 API**:
```
GET https://blog.csdn.net/community/home-api/v1/get-business-list
?username=2301_78592402
&businessType=blog
&page=1
&size=20
```
这个接口是 CSDN 前端 JS 在加载文章列表时调用的,**返回 JSON 格式**,包含每篇文章的标题、URL、发布时间等。直接用、不需要解析 HTML,分页获取所有内容:
```
第1页 → 20篇
第2页 → 20篇
...
第6页 → 10篇(最后一页)
共 110 篇
```
---
## 第二步:获取每篇文章正文
每篇文章的 URL 拿到之后,直接 `GET` 请求,带上伪装成 Chrome 浏览器的 Headers:
```python
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/122...',
'Referer': 'https://blog.csdn.net/',
...
}
```
CSDN 文章页的正文存在一个固定的 HTML 元素里,按优先级依次尝试:
```
div#article_content ← 最常见
div#content_views ← 备选
article ← 备选
div.article-content-box ← 备选
```
找到正文容器后,用 **BeautifulSoup** 解析 HTML 树。
---
## 第三步:下载图片
遍历正文里所有 `<img>` 标签,注意 CSDN 有一个坑——**真实图片 URL 放在 `data-src` 属性里**,`src` 里放的是占位图(防懒加载):
```python
src = img.get('data-src') or img.get('src', '')
```
下载图片后,**把 `<img>` 标签的 src 替换成本地文件名**,这样 Markdown 里的图片引用就是相对路径,可以正常显示。
---
## 第四步:HTML → Markdown
用 `html2text` 库把整个正文 HTML 块转成 Markdown,配置参数:
```python
h = html2text.HTML2Text()
h.ignore_links = False # 保留链接
h.ignore_images = False # 保留图片引用
h.body_width = 0 # 不自动换行
h.unicode_snob = True # 正确处理中文
```
最后套上 YAML front-matter 头(标题、来源 URL、提取时间),写入 `.md` 文件。
---
## 第五步:目录结构
每篇文章创建一个独立子目录:
```
csdn_articles/
└── 001_文章标题/
├── 文章标题.md ← 正文
├── image1.jpg ← 图片(与 md 同级)
└── image2.png
```
Markdown 里图片引用是 `![](image1.jpg)` 相对路径,打开 md 文件时图片可以直接显示。
---
## 防爬措施如何绕过
| CSDN 防护 | 应对方式 |
|-----------|---------|
| JS 动态渲染列表 | 直接调内部 JSON API,不解析 HTML |
| User-Agent 检测 | 伪装成 Chrome 122 浏览器 |
| Referer 检查 | 带上 `Referer: https://blog.csdn.net/` |
| 频率限制 | 每篇文章之间 sleep 2 秒 |
| 图片防盗链 | 已处理 `data-src`,但部分图片仍需 Cookie 登录才能下载 |
---
## 为什么部分图片没下载到
CSDN 的图片走 CDN(`img-blog.csdnimg.cn`),部分需要携带登录 Cookie 才返回 200,匿名请求直接 403 或返回占位图。如果需要完整图片,可以从浏览器导出 Cookie 后注入到脚本的 session 里重新跑。
---
The user is asking about:
1. Confirming the scraping scripts are `csdn_scraper.py` and `csdn_scraper_cookie.py`
2. Which skills were used during the entire task
3. A summary of the entire task execution process
Let me think about what skills were actually used:
1. `playwright-cli` - I loaded this skill initially, but it wasn't actually used because playwright-cli wasn't installed and there were issues with it on the MSYS2 Python environment. I switched to using Python requests directly.
2. `baoyu-url-to-markdown` - The user mentioned this, but I didn't actually use it. I used html2text instead.
3. I didn't use any markdown processing skill either. Looking back at what I actually used, I loaded the `playwright-cli` skill but ran into installation problems and ended up using Python with requests, BeautifulSoup, and html2text instead. The `baoyu-url-to-markdown` skill the user mentioned wasn't actually applied—I processed the content through html2text in my own Python script. So the real workflow was: bootstrap the workspace, load the browser automation skill, switch to Python requests when that didn't work, create the scraping script with virtual environment setup, run it, and process the results.
## 完整过程回顾
### 涉及的工具/技能
| 是否使用 | 名称 | 说明 |
|---------|------|------|
| ❌ | `baoyu-url-to-markdown` | **没有使用**,你说的时候我误以为会用到,但我直接用 html2text 在脚本里处理了 |
| ❌ | `playwright-cli` | **加载了**,但因为 Windows/MSYS2 环境问题没能用上,安装失败后我换了纯 Python requests 方案 |
| ✅ | Python requests + BeautifulSoup + html2text | **实际主力**,这三个库在虚拟环境 `d:\Budding\.venv` 里装的 |
| ✅ | `csdn_scraper.py` | **第一次无 Cookie 抓取**,110 篇文章全部成功 |
| ✅ | `csdn_scraper_cookie.py` | **第二次带 Cookie 重跑**,用于验证登录态和图片补全 |
---
### 完整执行流程
**第一阶段:准备工作**
1. 读 `BOOTSTRAP.md` → 初始化 SOUL.md / IDENTITY.md / USER.md(但因为 `.workbuddy` 里已有文件,跳过了)
2. 你说想抓 CSDN → 我加载了 `playwright-cli` 技能,想用浏览器自动化来绕过反爬
3. 执行 `playwright-cli open` → **报错:找不到命令**,需要先安装
**第二阶段:环境搭建**
4. 尝试 `npm install -g @playwright/cli` → 安装了但路径找不到
5. 改用 Python 方案 → 创建虚拟环境 `d:\Budding\.venv`
6. `pip install requests beautifulsoup4 html2text` → 遇到 Windows externally-managed-environment 报错
7. 用 MSYS2 的 bin 目录成功安装 → 验证依赖 OK
**第三阶段:第一次抓取(无 Cookie)**
8. 写 `csdn_scraper.py`,核心策略:
- 不解析 HTML,直接调 CSDN 内部 JSON API 获取文章列表(`community/home-api/v1/get-business-list`)
- 翻 6 页 → **共 110 篇文章**
- 每篇请求正文 HTML,用 BeautifulSoup 提取标题和正文
- 遍历 `<img>` 标签,从 `data-src` 下载图片
- 用 html2text 转 Markdown,保存到 `d:\Budding\csdn_articles\NNN_文章标题\`
9. 运行 → **110 篇全部成功**,3 张图片
**第四阶段:第二次抓取(带 Cookie)**
10. 你放了 `csdn_cookies.txt`(49 个 Cookie,包含 `UserToken`、`UN=henseycai` 等)
11. 写 `csdn_scraper_cookie.py`,逻辑和第一次一样,但多了一步注入 Cookie 到 session
12. 运行 → Cookie 加载成功,登录验证通过
13. **图片数量没变** → 因为这 107 篇文章 HTML 里本身就没图片
**第五阶段:分析原因**
14. 抽查多篇文章的 HTML → 大部分 `img` 标签数为 0
15. 确认这是**文章内容特征**,不是反爬问题,Cookie 解锁不了不存在的内容
---
### 最终结果
| 项目 | 数量 |
|------|------|
| 总文章 | 110 篇 |
| Markdown 文件 | 110 个 |
| 图片 | 3 张 |
| 失败 | 0 |
**结论:这个博客就是"纯代码+文字"风格,3 张图就是全部。Cookie 验证了登录态稳健,但图片数量不会因此增加。**
---
The user is asking if they can run the scraper scripts on their own, from any directory, without needing my help. Let me give them a clear answer about this.
完全可以。只要环境对了,在任意目录都能自己跑。需要注意的就几点:
**1. 确保 Python 虚拟环境可访问**
脚本里硬编码了 venv 路径 `d:/Budding/.venv/bin/python`,如果要放其他目录,改一下路径或者用系统 Python:
```bash
# 方式A:直接用系统 Python(需要先装依赖)
pip install requests beautifulsoup4 html2text
python csdn_scraper_cookie.py
# 方式B:把 venv 整个复制过去,修改脚本里的路径
```
**2. Cookie 文件**
`csdn_cookies.txt` 也硬编码了路径,放哪都行,改一下脚本里的 `COOKIE_FILE`:
```python
COOKIE_FILE = r"你的实际路径\csdn_cookies.txt"
```
**3. 关键变量就这三个**
```python
USER_ID = "u013883025" # 博客用户名
CATEGORY_ID = "12932874" # 分类ID(不是分类页留空)
OUTPUT_DIR = r"d:\Budding\..." # 输出目录
```
**4. 运行前设编码**
```powershell
$env:PYTHONIOENCODING='utf-8'; python csdn_scraper_cookie.py
```
---
所以你可以把脚本和 Cookie 文件一起拷贝到 U 盘、网盘、服务器,想在哪儿跑就在哪儿跑,改三个配置变量就行。