python爬虫实战(9)--获取澎pai热榜

1. 需要的类包

复制代码
import pandas as pd
import requests

2. 请求地址

通过分析,数据可以直接从接口获取,无需解析页面标签,直接取出我们需要的数据即可。

复制代码
def fetch_hot_news(api_url):
    response = requests.get(api_url)

    if response.status_code == 200:
        data = response.json()
        hot_news = data.get("data", {}).get("hotNews", [])
        return hot_news
    else:
        print(f"Failed to retrieve data. Status code: {response.status_code}")
        return []

3. 导出表格

复制代码
def export_to_excel(hot_news_data):
    if not hot_news_data:
        return

    # Add the missing URL field
    base_url = "https://www.xxx.cn/newsDetail_forward_" #澎某pai
    hot_news_data = [{
        **news,
        "URL": f"{base_url}{news['contId']}"
    } for news in hot_news_data]

    # Create a DataFrame
    df = pd.DataFrame(hot_news_data)

    # Choose only relevant columns
    relevant_columns = ["contId", "name", "pubTime", "URL"]
    df = df[relevant_columns]

    # Export to Excel
    df.to_excel("pengpai-top.xlsx", index=False)
    print("Data exported to Excel successfully.")

处理url

复制代码
def main():
    api_url = "https:/xx/wwwIndex/xxx" #分析得到的需要请求的接口地址
    hot_news_data = fetch_hot_news(api_url)

    if hot_news_data:
        export_to_excel(hot_news_data)
    else:
        print("No hot news data found.")

4. 成果展示

相关推荐
IT陈图图2 小时前
构建 Flutter × OpenHarmony 跨端带文本输入对话框示例
开发语言·javascript·flutter
叫我辉哥e17 小时前
### 技术文章大纲:C语言造轮子大赛
c语言·开发语言
Hgfdsaqwr8 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
guygg888 小时前
NOMA功率分配与64 QAM调制中的SIC的MATLAB仿真
开发语言·matlab
开发者小天8 小时前
python中For Loop的用法
java·服务器·python
flushmeteor8 小时前
JDK源码-基础类-String
java·开发语言
老百姓懂点AI8 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
u0109272719 小时前
C++中的策略模式变体
开发语言·c++·算法
雨季66610 小时前
构建 OpenHarmony 简易文字行数统计器:用字符串分割实现纯文本结构感知
开发语言·前端·javascript·flutter·ui·dart
雨季66610 小时前
Flutter 三端应用实战:OpenHarmony 简易倒序文本查看器开发指南
开发语言·javascript·flutter·ui