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

相关推荐
前端 贾公子21 小时前
v-if 与 v-for 的优先级对比
开发语言·前端·javascript
嗯嗯=1 天前
python学习篇
开发语言·python·学习
WoY20201 天前
opencv-python在ubuntu系统中缺少依赖
python·opencv·ubuntu
大游小游之老游1 天前
Python中如何实现一个程序运行时,调用另一文件中的函数
python
mantch1 天前
个人 LLM 接口服务项目:一个简洁的 AI 入口
人工智能·python·llm
不会c嘎嘎1 天前
QT中的常用控件 (二)
开发语言·qt
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
是一个Bug1 天前
50道核心JVM面试题
java·开发语言·面试
朱朱没烦恼yeye1 天前
java基础学习
java·python·学习
她和夏天一样热1 天前
【观后感】Java线程池实现原理及其在美团业务中的实践
java·开发语言·jvm