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

相关推荐
斑点鱼 SpotFish7 分钟前
用Python可视化国庆期间旅游概况与消费趋势
开发语言·python·旅游
小兔崽子去哪了9 分钟前
Python 学习记录
python
only-lucky9 分钟前
在Qt中使用VTK
开发语言·qt
埃泽漫笔30 分钟前
RabbitMQ四种交换机详解
python·mq
小杰帅气31 分钟前
类与对象1
开发语言·c++
chenyuhao202442 分钟前
《C++二叉引擎:STL风格搜索树实现与算法优化》
开发语言·数据结构·c++·后端·算法
小猪快跑爱摄影1 小时前
【附代码】Jupyter 多进程调用 seaborn 并保留格式
python·jupyter
空荡forevere1 小时前
《操作系统真象还原》 第十章 输入输出系统
开发语言·c++·操作系统
技术猴小猴1 小时前
如何使用Python实现LRU缓存
python·spring·缓存
2401_841495641 小时前
【自然语言处理】“bert-base-chinese”的基本用法及实战案例
人工智能·python·自然语言处理·bert·文本预处理·特征提取·训练验证