【python】爬取知乎热榜Top50保存到Excel文件中【附源码】

欢迎来到英杰社区icon-default.png?t=N7T8https://bbs.csdn.net/topics/617804998

   一、导入必要的模块:

    这篇博客将介绍如何使用Python编写一个爬虫程序,从斗鱼直播网站上获取图片信息并保存到本地。我们将使用requests模块发送HTTP请求和接收响应,以及os模块处理文件和目录操作。

        如果出现模块报错

        进入控制台输入:建议使用国内镜像源

pip install requests -i https://mirrors.aliyun.com/pypi/simple

         我大致罗列了以下几种国内镜像源:

        

清华大学
https://pypi.tuna.tsinghua.edu.cn/simple

阿里云
https://mirrors.aliyun.com/pypi/simple/

豆瓣
https://pypi.douban.com/simple/ 

百度云
https://mirror.baidu.com/pypi/simple/

中科大
https://pypi.mirrors.ustc.edu.cn/simple/

华为云
https://mirrors.huaweicloud.com/repository/pypi/simple/

腾讯云
https://mirrors.cloud.tencent.com/pypi/simple/

    

二、发送GET请求获取响应数据:

        设置了请求头部信息,以模拟浏览器的请求,函数返回响应数据的JSON格式内容。

def get_html(url):
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
    }
    response = requests.get(url=url, headers=header)
    # print(response.json())
    html = response.json()
    return html

        如何获取请求头:

        火狐浏览器:

  1. 打开目标网页并右键点击页面空白处。
  2. 选择“检查元素”选项,或按下快捷键Ctrl + Shift + C(Windows)
  3. 在开发者工具窗口中,切换到“网络”选项卡。
  4. 刷新页面以捕获所有的网络请求。
  5. 在请求列表中选择您感兴趣的请求。
  6. 在右侧的“请求标头”或“Request Headers”部分,即可找到请求头信息。

     将以下请求头信息复制出来即可

三、代码实现

这段代码是用来爬取知乎热榜数据并保存到 Excel 文件中的。具体实现方法如下:

  1. 定义了一个函数 get_time,用于获取当前时间,并可以按照指定的格式进行输出。

def get_time(fmt:str='%Y-%m-%d %H-%M-%S') -> str:
    '''
    获取当前时间
    '''
    ts = time.time()
    ta = time.localtime(ts)
    t = time.strftime(fmt, ta)
    return t
  1. 定义了一个函数 save_hot_list,用于保存热榜数据到 Excel 文件中。

def save_hot_list() -> None:
    # 请求头
    headers = {
​
        'User-Agent': 'osee2unifiedRelease/4318 osee2unifiedReleaseVersion/7.7.0 Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
        'Host': 'api.zhihu.com',
​
​
    }
    # 请求参数
    params = (
        ('limit', '50'),
        ('reverse_order', '0'),
    )
    # 发送请求
    response = requests.get(
        'https://zhihu.com/topstory/hot-list', headers=headers, params=params)
​
    items = response.json()['data']

首先定义请求头和请求参数,然后发送 GET 请求获取知乎热榜数据。其中 response.json()['data'] 取出了返回结果中的 data 字段,即热榜列表数据。

    rows = []
    now = get_time()
    # 取日期为文件夹名称
    dir_path = now.split(' ')[0]
    # 文件夹不存在则创建
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

定义一个空列表 rows 来存储热榜数据,然后获取当前时间并将其拆分为日期和时间两个部分。这里我们只需要日期部分作为保存数据的文件夹名称,如果这个文件夹不存在,则创建它。

  
  for rank, item in enumerate(items, start=1):
        target = item.get('target')
        title = target.get('title')
        answer_count = target.get('answer_count')
        hot = int(item.get('detail_text').split(' ')[0])
        follower_count = target.get('follower_count')
        question_url = target.get('url').replace(
            'api', 'www').replace('questions', 'question')
        rows.append({
            '排名': rank,
            '标题': title,
            '回答数': answer_count,
            '关注数': follower_count,
            '热度(万)': hot,
            '问题链接': question_url
        })

遍历全部热榜数据,并从中取出我们需要的属性,包括:标题、回答数、关注数、热度和问题链接。将这些属性添加到 rows 列表中。

    df = pd.DataFrame(rows)
    now = get_time()
    excel_path = dir_path+'/Yan-英杰.xlsx'
    df.to_excel(excel_path, index=None)
    print(now, '的热榜数据数据已保存到文件', excel_path)

rows 列表转化为 Pandas 的 DataFrame,并将其保存到 Excel 文件中。Excel 文件的名称以当前日期作为文件夹名称,以 “Yan-英杰.xlsx” 作为文件名。最后输出保存完成的信息。

# 保存热榜数据
save_hot_list()

调用 save_hot_list 函数来执行保存操作。

四、效果图:

五、完整代码

import requests
import pandas as pd
import time
import os


def get_time(fmt:str='%Y-%m-%d %H-%M-%S') -> str:
    '''
    获取当前时间
    '''
    ts = time.time()
    ta = time.localtime(ts)
    t = time.strftime(fmt, ta)
    return t


def save_hot_list() -> None:
    # 请求头
    headers = {

        'User-Agent': 'osee2unifiedRelease/4318 osee2unifiedReleaseVersion/7.7.0 Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
        'Host': 'api.zhihu.com',


    }
    # 请求参数
    params = (
        ('limit', '50'),
        ('reverse_order', '0'),
    )
    # 发送请求
    response = requests.get(
        'https://zhihu.com/topstory/hot-list', headers=headers, params=params)

    items = response.json()['data']
    rows = []
    now = get_time()
    # 取日期为文件夹名称
    dir_path = now.split(' ')[0]
    # 文件夹不存在则创建
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    # 遍历全部热榜,取出几个属性
    for rank, item in enumerate(items, start=1):
        target = item.get('target')
        title = target.get('title')
        answer_count = target.get('answer_count')
        hot = int(item.get('detail_text').split(' ')[0])
        follower_count = target.get('follower_count')
        question_url = target.get('url').replace(
            'api', 'www').replace('questions', 'question')
        rows.append({
            '排名': rank,
            '标题': title,
            '回答数': answer_count,
            '关注数': follower_count,
            '热度(万)': hot,
            '问题链接': question_url
        })
    df = pd.DataFrame(rows)
    now = get_time()
    excel_path = dir_path+'/Yan-英杰.xlsx'
    df.to_excel(excel_path, index=None)
    print(now, '的热榜数据数据已保存到文件', excel_path)

# 保存热榜数据
save_hot_list()

   给大家推荐一个网站

    IT今日热榜 一站式资讯平台

        里面包含了上百个IT网站,欢迎大家访问:IT今日热榜 一站式资讯平台

   iToday,打开信息的新时代。作为一家创新的IT数字媒体平台,iToday致力于为用户提供最新、最全面的IT资讯和内容。里面包含了技术资讯、IT社区、面试求职、前沿科技等诸多内容。我们的团队由一群热爱创作的开发者和分享的专业编程知识爱好者组成,他们精选并整理出真实可信的信息,确保您获得独特、有价值的阅读体验。随时随地,尽在iToday,与世界保持连接,开启您的信息新旅程!

IT今日热榜 一站式资讯平台IT今日热榜汇聚各类IT热榜:虎嗅、知乎、36氪、京东图书销售、晚点、全天候科技、极客公园、GitHub、掘金、CSDN、哔哩哔哩、51CTO、博客园、GitChat、开发者头条、思否、LeetCode、人人都是产品经理、牛客网、看准、拉勾、Boss直聘http://itoday.top/#/

版权声明:本文为博主作者:Yan-英杰原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/m0_73367097/article/details/135465445

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2024年1月16日
下一篇 2024年1月16日

相关推荐