Scrapy 爬虫框架:爬取知乎热榜完整教程
·
Scrapy 爬虫框架:爬取知乎热榜完整教程
1. 环境准备
安装 Scrapy 框架:
pip install scrapy
2. 创建项目
在终端执行:
scrapy startproject zhihu_hot
cd zhihu_hot
scrapy genspider hotlist www.zhihu.com/billboard
3. 定义数据结构
修改 items.py:
import scrapy
class ZhihuHotItem(scrapy.Item):
rank = scrapy.Field() # 排名
title = scrapy.Field() # 标题
hot_score = scrapy.Field() # 热度值
url = scrapy.Field() # 链接
4. 编写爬虫逻辑
修改 spiders/hotlist.py:
import scrapy
from zhihu_hot.items import ZhihuHotItem
class HotlistSpider(scrapy.Spider):
name = 'hotlist'
allowed_domains = ['www.zhihu.com']
start_urls = ['https://www.zhihu.com/billboard']
def parse(self, response):
for item in response.css('div.HotList-item'):
yield ZhihuHotItem(
rank=item.css('div.HotList-itemIndex::text').get().strip(),
title=item.css('div.HotList-itemTitle::text').get().strip(),
hot_score=item.css('div.HotList-itemMetrics::text').get().strip(),
url=item.css('a::attr(href)').get()
)
5. 配置请求头
修改 settings.py 添加:
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
DOWNLOAD_DELAY = 2 # 降低请求频率
FEED_FORMAT = 'json'
FEED_URI = 'zhihu_hot.json' # 输出文件名
6. 运行爬虫
scrapy crawl hotlist
7. 数据处理(可选)
添加 pipelines.py 数据清洗:
class ZhihuHotPipeline:
def process_item(self, item, spider):
# 移除热度值中的"万"字并转换为整数
if '万' in item['hot_score']:
item['hot_score'] = int(float(item['hot_score'].replace('万', '')) * 10000)
return item
在 settings.py 中启用管道:
ITEM_PIPELINES = {'zhihu_hot.pipelines.ZhihuHotPipeline': 300}
8. 完整代码结构
zhihu_hot/
├── scrapy.cfg
├── zhihu_hot/
│ ├── __init__.py
│ ├── items.py
│ ├── middlewares.py
│ ├── pipelines.py
│ ├── settings.py
│ └── spiders/
│ ├── __init__.py
│ └── hotlist.py
9. 常见问题解决
- 403 错误:更新
USER_AGENT或添加 Cookie - 数据为空:检查 CSS 选择器是否匹配最新页面结构
- 请求限制:增加
DOWNLOAD_DELAY或使用代理 IP - JSON 编码错误:添加
FEED_EXPORT_ENCODING = 'utf-8'到settings.py
10. 进阶优化
# 在爬虫类中添加自定义请求头
custom_headers = {
'Accept-Language': 'zh-CN,zh;q=0.9',
'Referer': 'https://www.zhihu.com/'
}
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, headers=self.custom_headers)
执行后将在当前目录生成
zhihu_hot.json文件,包含结构化数据:[ { "rank": "1", "title": "如何评价某新发布的产品", "hot_score": 2500000, "url": "https://www.zhihu.com/question/123456" }, ... ]
注意事项:
- 知乎页面可能更新,需定期调整 CSS 选择器
- 高频访问可能触发反爬,建议设置
DOWNLOAD_DELAY ≥ 3 - 完整代码参考 GitHub:[username/zhihu-hot-scraper](示例仓库)
更多推荐
所有评论(0)