手把手教你用DrissionPage搭建个人新闻聚合器:自动抓取百度热搜并保存到Excel
用DrissionPage打造智能新闻聚合器从百度热搜抓取到Excel自动化分析每天手动刷新闻不仅耗时还容易错过重要信息。想象一下如果有个私人助手能自动收集全网热点整理成结构化的报告甚至生成直观的可视化图表——这就是我们今天要构建的智能新闻聚合器。不同于简单的文本抓取我们将使用Python生态中的轻量级工具DrissionPage结合pandas和matplotlib打造一个从数据采集、清洗到分析的全流程解决方案。1. 环境配置与基础工具链搭建工欲善其事必先利其器。在开始自动化之旅前我们需要配置一个稳定高效的开发环境。这里推荐使用Python 3.8版本它能完美兼容我们将要用到的所有库。首先创建并激活虚拟环境这是避免依赖冲突的最佳实践python -m venv news_venv source news_venv/bin/activate # Linux/Mac news_venv\Scripts\activate # Windows接下来安装核心工具包pip install DrissionPage pandas openpyxl matplotlib wordcloud为什么选择这些工具DrissionPage相比传统Selenium更轻量且对中文文档友好pandas是数据处理的事实标准openpyxl用于Excel操作matplotlib和wordcloud则负责可视化呈现。验证安装是否成功from DrissionPage import ChromiumPage import pandas as pd print(所有依赖库已就绪)如果系统提示缺少Chromium浏览器DrissionPage会自动下载所需版本你也可以通过以下命令指定Chromium路径page ChromiumPage(browser_path/path/to/chromium)2. 网页自动化核心技巧高效抓取百度热搜百度热搜是了解当下热点的重要窗口但其DOM结构经常变动需要动态适应。我们先分析2023年新版百度首页的热搜区域结构。典型的热搜条目XPath路径如下//*[idhotsearch-content-wrapper]/li[1]/a/span[2]但更稳健的做法是使用相对路径和属性组合定位hot_items page.eles(xpath://li[contains(class, hotsearch-item)]) for item in hot_items: title item.ele(tag:spanclasstitle-content-title).text heat item.ele(tag:spanclasstitle-content-hot).text print(f{title}: {heat})反爬策略应对方案随机延时import random; time.sleep(random.uniform(1, 3))请求头伪装page.set.header({User-Agent: Mozilla/5.0})IP轮换结合代理池使用需自行实现将抓取逻辑封装成函数def fetch_baidu_hotsearch(page): page.get(https://www.baidu.com) hot_data [] items page.eles(xpath://li[contains(class, hotsearch-item)])[:10] for idx, item in enumerate(items, 1): hot_data.append({ rank: idx, title: item.ele(tag:spanclasstitle-content-title).text, heat: int(item.ele(tag:spanclasstitle-content-hot).text[:-1]), timestamp: pd.Timestamp.now() }) return hot_data3. 多源新闻聚合与数据标准化处理单一来源可能产生信息偏差我们需要扩展数据采集范围。以下是主流新闻平台的特征分析平台名称热点区域XPath特征反爬强度数据质量百度热搜class包含hotsearch-item中等实时性强微博热搜class包含Texta严格娱乐倾向知乎热榜data-za-detail-view-element_name宽松深度内容今日头条xpath://div[classtitle-box]严格综合资讯构建统一采集管道def fetch_multisource_news(): sources { weibo: fetch_weibo_hot, zhihu: fetch_zhihu_hot, toutiao: fetch_toutiao_news } all_data [] with ChromiumPage() as page: for name, fetcher in sources.items(): try: all_data.extend(fetcher(page)) time.sleep(2) except Exception as e: print(f{name}采集失败: {str(e)}) return pd.DataFrame(all_data)数据清洗关键步骤去重df.drop_duplicates(subset[title], keepfirst)缺失值处理df[heat].fillna(0, inplaceTrue)格式统一df[timestamp] pd.to_datetime(df[timestamp])文本清洗import re df[title] df[title].apply(lambda x: re.sub(r\s, , x).strip())4. 高级存储与可视化从Excel到词云结构化存储是数据分析的基础。我们使用pandas的ExcelWriter实现多sheet存储def save_to_excel(df, filename): with pd.ExcelWriter(filename, engineopenpyxl) as writer: # 原始数据表 df.to_excel(writer, sheet_nameRawData, indexFalse) # 聚合分析表 summary df.groupby(source)[heat].agg([mean, count]) summary.to_excel(writer, sheet_nameSummary) # 添加数据透视表 pivot df.pivot_table(indexsource, columnsdf[timestamp].dt.hour, valuesheat, aggfuncmean) pivot.to_excel(writer, sheet_nameHourlyTrend)生成专业级词云的完整代码from wordcloud import WordCloud import matplotlib.pyplot as plt def generate_wordcloud(texts): wc WordCloud( font_pathSimHei.ttf, width800, height600, background_colorwhite, collocationsFalse ) word_freq pd.Series( .join(texts).split()).value_counts() wc.generate_from_frequencies(word_freq) plt.figure(figsize(12, 8)) plt.imshow(wc, interpolationbilinear) plt.axis(off) plt.savefig(hotword_cloud.png, dpi300, bbox_inchestight)更进阶的时间序列分析def plot_trend(df): plt.style.use(seaborn) fig, ax plt.subplots(figsize(12, 6)) for source in df[source].unique(): subset df[df[source] source] subset.set_index(timestamp)[heat].plot(axax, labelsource) ax.set_title(热搜热度趋势对比) ax.set_ylabel(热度指数) ax.legend() fig.savefig(trend_comparison.png)5. 项目优化与生产级部署基础功能实现后我们需要考虑系统的健壮性和可维护性。以下是几个关键优化方向错误处理机制增强class NewsFetcher: def __init__(self): self.retry_limit 3 self.timeout 30 def safe_fetch(self, url): for attempt in range(self.retry_limit): try: page.get(url, timeoutself.timeout) return True except TimeoutError: print(f尝试 {attempt 1} 次超时) time.sleep(5) return False配置化管理 创建config.yaml文件sources: baidu: url: https://www.baidu.com xpath: //li[contains(class, hotsearch-item)] weibo: url: https://s.weibo.com/top/summary xpath: //td[classtd-02]定时任务集成 使用APScheduler创建后台任务from apscheduler.schedulers.blocking import BlockingScheduler sched BlockingScheduler() sched.scheduled_job(cron, hour8,12,18, minute30) def scheduled_job(): df fetch_multisource_news() save_to_excel(df, fnews_{datetime.now().strftime(%Y%m%d)}.xlsx) sched.start()日志记录系统import logging logging.basicConfig( filenamenews_collector.log, levellogging.INFO, format%(asctime)s - %(levelname)s - %(message)s ) try: main_process() except Exception as e: logging.error(f采集任务失败: {str(e)}, exc_infoTrue)6. 扩展应用场景与商业价值挖掘这个新闻聚合器的潜力远不止个人使用。以下是几个高价值扩展方向企业舆情监控系统添加关键词告警机制情感分析集成使用SnowNLP或BERT竞品动态追踪from snownlp import SnowNLP def analyze_sentiment(title): s SnowNLP(title) return s.sentiments # 返回0-1之间的情感分值自媒体内容助手热点话题自动发现爆款标题生成内容相似度检测数据产品开发生成每日热点简报PDF开发REST API供内部调用构建可视化Dashboardfrom flask import Flask, jsonify app Flask(__name__) app.route(/api/hotnews) def get_hotnews(): data fetch_multisource_news() return jsonify(data.to_dict(orientrecords))实际部署时可以考虑使用Docker容器化FROM python:3.9 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD [python, scheduler.py]我在实际项目中发现这套系统最耗时的部分其实是反爬对抗。一个实用的技巧是维护多个用户代理轮换列表并动态调整请求频率。另一个坑是Chromium的内存泄漏问题建议定期重启浏览器实例或者使用无头模式减少资源消耗。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2467128.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!