基于Scrapy框架的今日头条热榜数据爬取实战
本文介绍了使用Scrapy框架爬取今日头条热榜数据的方法。项目通过分析网页结构,定位<table>标签中的热榜数据,使用XPath提取标题、热度和链接信息。核心步骤包括:配置Scrapy环境、定义数据模型、编写爬虫逻辑、实现CSV存储管道。针对动态加载和反爬问题,提出了Selenium模拟浏览器和随机User-Agent等解决方案。最终生成结构化CSV文件,为后续数据分析和可视化提供基
·
一、项目背景与目标
今日头条热榜(https://tophub.today/n/x9ozB4KoXb)是一个实时更新的热门话题聚合平台,涵盖新闻、娱乐、科技等多领域榜单。本项目旨在通过 Scrapy框架 爬取热榜数据,包括标题、热度、链接等信息,并存储为结构化数据(如CSV)。
二、环境准备与工具选择
- 技术栈:
- Scrapy:Python爬虫框架,支持异步请求、高效解析。
- XPath/CSS Selector:定位HTML节点。
- CSV:存储结构化数据。
- 环境配置:
pip install scrapy scrapy startproject toutiao_hotlist cd toutiao_hotlist scrapy genspider toutiao tophub.today
三、网页结构分析与数据定位
- 页面特征:
- 目标URL为动态加载的榜单页面(需观察是否为静态HTML)。
- 榜单数据位于
<table class="table">
标签内,每行数据为<tr>
标签。 - 标题位于
<td[2]/a>
,热度位于<td[3]>
,链接为标题的href
属性。
- XPath定位示例:
# 提取所有榜单表格 tables = response.xpath('//table[@class="table"]') # 遍历每行数据 for tr in tables.xpath('.//tr')[1:]: # 跳过表头 title = tr.xpath('./td[2]/a/text()').get() heat = tr.xpath('./td[3]/text()').get() link = tr.xpath('./td[2]/a/@href').get()
四、Scrapy爬虫代码实现
-
定义Item(
items.py
)import scrapy class ToutiaoItem(scrapy.Item): title = scrapy.Field() # 标题 heat = scrapy.Field() # 热度 link = scrapy.Field() # 链接
-
编写Spider(
spiders/toutiao.py
)import scrapy from toutiao_hotlist.items import ToutiaoItem class ToutiaoSpider(scrapy.Spider): name = 'toutiao' allowed_domains = ['tophub.today'] start_urls = ['https://tophub.today/n/x9ozB4KoXb'] def parse(self, response): # 定位所有榜单表格 tables = response.xpath('//table[@class="table"]') for table in tables: # 提取每行数据 rows = table.xpath('.//tr')[1:] # 跳过表头 for row in rows: item = ToutiaoItem() item['title'] = row.xpath('./td[2]/a/text()').get() item['heat'] = row.xpath('./td[3]/text()').get() item['link'] = row.xpath('./td[2]/a/@href').get() yield item
-
配置管道(
pipelines.py
)import csv class ToutiaoPipeline: def __init__(self): self.file = open('hotlist.csv', 'w', newline='', encoding='utf-8') self.writer = csv.writer(self.file) self.writer.writerow(['标题', '热度', '链接']) # 写入表头 def process_item(self, item, spider): self.writer.writerow([ item['title'], item['heat'], item['link'] ]) return item def close_spider(self, spider): self.file.close()
-
启用管道(
settings.py
)ITEM_PIPELINES = { 'toutiao_hotlist.pipelines.ToutiaoPipeline': 300, }
五、运行与结果验证
- 执行爬虫:
scrapy crawl toutiao -o hotlist.csv
- 数据验证:
- 检查生成的
hotlist.csv
文件,确保标题、热度、链接字段完整。 - 示例输出:
标题 热度 链接 某明星出轨事件 1.2万 /n/xxx
- 检查生成的
六、难点与解决方案
-
动态加载问题:
- 若页面通过JavaScript渲染,需使用 Scrapy+Selenium 或 Splash 模拟浏览器。
- 示例中间件配置:
from scrapy_selenium import SeleniumRequest class ToutiaoSpider(scrapy.Spider): def start_requests(self): yield SeleniumRequest(url=self.start_urls[0], callback=self.parse)
-
反爬机制应对:
- User-Agent随机化:在
settings.py
中配置用户代理池。 - 延迟设置:
DOWNLOAD_DELAY = 2 # 降低请求频率
- User-Agent随机化:在
七、扩展方向
- 多榜单抓取:遍历所有分类(如微博、知乎、百度榜单)。
- 数据清洗:使用正则表达式提取热度数值(如
(\d+\.?\d*)
)。 - 可视化分析:将CSV数据导入Python(
pandas
)生成热力图或趋势图。
总结
通过Scrapy框架可高效爬取今日头条热榜数据,核心步骤包括:
- 分析网页结构,定位数据节点;
- 定义Item和Pipeline实现数据存储;
- 应对动态加载与反爬机制。
更多推荐
所有评论(0)