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

相关推荐
李白同学13 分钟前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?1 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
失败尽常态5232 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447742 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农2 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿2 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing2 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
彳卸风2 小时前
Unable to parse timestamp value: “20250220135445“, expected format is
开发语言
dorabighead3 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
xinxiyinhe3 小时前
如何设置Cursor中.cursorrules文件
人工智能·python