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

相关推荐
沐知全栈开发7 小时前
HTML5 浏览器支持
开发语言
wasp5207 小时前
AgentScope Java 核心架构深度解析
java·开发语言·人工智能·架构·agentscope
WHOVENLY7 小时前
【javaScript】- 笔试题合集(长期更新,建议收藏,目前已更新至31题)
开发语言·前端·javascript
free-elcmacom8 小时前
深度学习<4>高效模型架构与优化器的“效率革命”
人工智能·python·深度学习·机器学习·架构
慌糖8 小时前
流-为序列化解释
开发语言
liliangcsdn8 小时前
python模拟beam search优化LLM输出过程
人工智能·python
LXS_3578 小时前
Day 18 C++提高 之 STL常用容器(string、vector、deque)
开发语言·c++·笔记·学习方法·改行学it
王琦03189 小时前
Python 函数详解
开发语言·python
胡伯来了9 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…9 小时前
Python 中的多层继承
开发语言·python