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. 成果展示

相关推荐
临床数据科学和人工智能兴趣组1 分钟前
要使用 R Markdown,首先需要安装 R 和 RStudio,接着安装 rmarkdown 包
开发语言·数据挖掘·数据分析·r语言·r语言-4.2.1
软萌萌的118 分钟前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Nebula嵌入式27 分钟前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
Dxy12393102161 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
神罚天下ET2 小时前
c# ACME client (补充)
开发语言·c#
小灰灰搞电子3 小时前
Qt 实现魔法导航菜单源码分享
开发语言·qt
持敬chijing3 小时前
Python概述
开发语言·python
赤羽尾风4 小时前
NumPy快速入门
python·numpy
倒流时光三十年5 小时前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django