Python爬取知乎评论:多线程与异步爬虫的性能优化

简介: Python爬取知乎评论:多线程与异步爬虫的性能优化
  1. 知乎评论爬取的技术挑战
    知乎的评论数据通常采用动态加载(Ajax),这意味着直接使用requests+BeautifulSoup无法获取完整数据。此外,知乎还设置了反爬机制,包括:
    ● 请求头(Headers)验证(如User-Agent、Referer)
    ● Cookie/Session 校验(未登录用户只能获取部分数据)
    ● 频率限制(频繁请求可能导致IP被封)
    因此,我们需要:
  2. 模拟浏览器请求(携带Headers和Cookies)
  3. 解析动态API接口(而非静态HTML)
  4. 优化爬取速度(多线程/异步)
  5. 获取知乎评论API分析
    (1)查找评论API
    打开知乎任意一个问题(如 https://www.zhihu.com/question/xxxxxx),按F12进入开发者工具,切换到Network选项卡,筛选XHR请求
    (2)解析评论数据结构
    评论通常嵌套在data字段中,结构如下:
    "data": [
     {
       "content": "评论内容",
       "author": { "name": "用户名" },
       "created_time": 1620000000
     }
    ],
    "paging": { "is_end": false, "next": "下一页URL" }
    }
    
    我们需要递归翻页(paging.next)爬取所有评论。
  6. Python爬取知乎评论的三种方式
    (1)单线程爬虫(基准测试)
    使用requests库直接请求API,逐页爬取:
    ```import requests
    import time

def fetch_comments(question_id, max_pages=5):
base_url = f"https://www.zhihu.com/api/v4/questions/{question_id}/answers"
headers = {
"User-Agent": "Mozilla/5.0",
"Cookie": "你的Cookie" # 登录后获取
}
comments = []
for page in range(max_pages):
url = f"{base_url}?offset={page * 10}&limit=10"
resp = requests.get(url, headers=headers).json()
for answer in resp["data"]:
comments.append(answer["content"])
time.sleep(1) # 避免请求过快
return comments

start_time = time.time()
comments = fetch_comments("12345678") # 替换为知乎问题ID
print(f"单线程爬取完成,耗时:{time.time() - start_time:.2f}秒")

缺点:逐页请求,速度慢(假设每页1秒,10页需10秒)。
(2)多线程爬虫(ThreadPoolExecutor)
使用concurrent.futures实现多线程并发请求:
```from concurrent.futures import ThreadPoolExecutor

def fetch_page(page, question_id):
    url = f"https://www.zhihu.com/api/v4/questions/{question_id}/answers?offset={page * 10}&limit=10"
    headers = {"User-Agent": "Mozilla/5.0"}
    resp = requests.get(url, headers=headers).json()
    return [answer["content"] for answer in resp["data"]]

def fetch_comments_multi(question_id, max_pages=5, threads=4):
    with ThreadPoolExecutor(max_workers=threads) as executor:
        futures = [executor.submit(fetch_page, page, question_id) for page in range(max_pages)]
        comments = []
        for future in futures:
            comments.extend(future.result())
    return comments

start_time = time.time()
comments = fetch_comments_multi("12345678", threads=4)
print(f"多线程爬取完成,耗时:{time.time() - start_time:.2f}秒")

优化点:
● 线程池控制并发数(避免被封)
● 比单线程快约3-4倍(4线程爬10页仅需2-3秒)
(3)异步爬虫(Asyncio + aiohttp)
使用aiohttp实现异步HTTP请求,进一步提高效率:
```import aiohttp
import asyncio
import time

代理配置

proxyHost = "www.16yun.cn"
proxyPort = "5445"
proxyUser = "16QMSOML"
proxyPass = "280651"

async def fetch_page_async(session, page, question_id):
url = f"https://www.zhihu.com/api/v4/questions/{question_id}/answers?offset={page * 10}&limit=10"
headers = {"User-Agent": "Mozilla/5.0"}
async with session.get(url, headers=headers) as resp:
data = await resp.json()
return [answer["content"] for answer in data["data"]]

async def fetch_comments_async(question_id, max_pages=5):

# 设置代理连接器
proxy_auth = aiohttp.BasicAuth(proxyUser, proxyPass)
connector = aiohttp.TCPConnector(
    limit=20,  # 并发连接数限制
    force_close=True,
    enable_cleanup_closed=True,
    proxy=f"http://{proxyHost}:{proxyPort}",
    proxy_auth=proxy_auth
)

async with aiohttp.ClientSession(connector=connector) as session:
    tasks = [fetch_page_async(session, page, question_id) for page in range(max_pages)]
    comments = await asyncio.gather(*tasks)
return [item for sublist in comments for item in sublist]

if name == "main":
start_time = time.time()
comments = asyncio.run(fetch_comments_async("12345678")) # 替换为知乎问题ID
print(f"异步爬取完成,耗时:{time.time() - start_time:.2f}秒")
print(f"共获取 {len(comments)} 条评论")
```
优势:
● 无GIL限制,比多线程更高效
● 适合高并发IO密集型任务(如爬虫)

  1. 性能对比与优化建议
    爬取方式 10页耗时(秒) 适用场景
    单线程 ~10 少量数据,简单爬取
    多线程(4线程) ~2.5 中等规模,需控制并发
    异步(Asyncio) ~1.8 大规模爬取,高并发需求
    优化建议
  2. 控制并发数:避免触发反爬(建议10-20并发)。
  3. 随机延迟:time.sleep(random.uniform(0.5, 2)) 模拟人类操作。
  4. 代理IP池:防止IP被封(如使用requests+ProxyPool)。
  5. 数据存储优化:异步写入数据库(如MongoDB或MySQL)。
相关文章
|
26天前
|
数据采集 存储 C++
Python异步爬虫(aiohttp)加速微信公众号图片下载
Python异步爬虫(aiohttp)加速微信公众号图片下载
|
27天前
|
数据采集 Web App开发 数据可视化
Python爬虫分析B站番剧播放量趋势:从数据采集到可视化分析
Python爬虫分析B站番剧播放量趋势:从数据采集到可视化分析b
|
24天前
|
数据采集 机器学习/深度学习 监控
代理IP并发控制:多线程爬虫的加速引擎
在数据采集领域,多线程爬虫结合代理IP并发控制技术,有效突破反爬机制。通过动态代理池与智能并发策略,显著提升采集效率并降低封禁率,成为高效数据抓取的关键方案。
58 0
|
24天前
|
数据采集 存储 Web App开发
Python爬虫库性能与选型实战指南:从需求到落地的全链路解析
本文深入解析Python爬虫库的性能与选型策略,涵盖需求分析、技术评估与实战案例,助你构建高效稳定的数据采集系统。
153 0
|
25天前
|
数据采集 监控 调度
干货分享“用 多线程 爬取数据”:单线程 + 协程的效率反超 3 倍,这才是 Python 异步的正确打开方式
在 Python 爬虫中,多线程因 GIL 和切换开销效率低下,而协程通过用户态调度实现高并发,大幅提升爬取效率。本文详解协程原理、实战对比多线程性能,并提供最佳实践,助你掌握异步爬虫核心技术。
|
25天前
|
数据采集 自然语言处理 分布式计算
大数据岗位技能需求挖掘:Python爬虫与NLP技术结合
大数据岗位技能需求挖掘:Python爬虫与NLP技术结合
|
4月前
|
数据采集 测试技术 C++
无headers爬虫 vs 带headers爬虫:Python性能对比
无headers爬虫 vs 带headers爬虫:Python性能对比
|
4月前
|
数据采集 存储 监控
Python 原生爬虫教程:网络爬虫的基本概念和认知
网络爬虫是一种自动抓取互联网信息的程序,广泛应用于搜索引擎、数据采集、新闻聚合和价格监控等领域。其工作流程包括 URL 调度、HTTP 请求、页面下载、解析、数据存储及新 URL 发现。Python 因其丰富的库(如 requests、BeautifulSoup、Scrapy)和简洁语法成为爬虫开发的首选语言。然而,在使用爬虫时需注意法律与道德问题,例如遵守 robots.txt 规则、控制请求频率以及合法使用数据,以确保爬虫技术健康有序发展。
617 31
|
3月前
|
数据采集 存储 NoSQL
分布式爬虫去重:Python + Redis实现高效URL去重
分布式爬虫去重:Python + Redis实现高效URL去重
|
9月前
|
数据采集 存储 JSON
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第27天】本文介绍了Python网络爬虫Scrapy框架的实战应用与技巧。首先讲解了如何创建Scrapy项目、定义爬虫、处理JSON响应、设置User-Agent和代理,以及存储爬取的数据。通过具体示例,帮助读者掌握Scrapy的核心功能和使用方法,提升数据采集效率。
394 6

热门文章

最新文章

推荐镜像

更多