【python】爬取斗鱼直播照片保存到本地目录

一、导入必要的模块:

    这篇博客将介绍如何使用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”部分,即可找到请求头信息。

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

3.解析响应数据中的图片信息

        用于解析响应数据中的图片信息。通过分析响应数据的结构,提取出每个图片的URL和标题,并将其存储在一个字典中,然后将所有字典组成的列表返回。
def parse_html(html):
    image_info_list = []
    for item in html['data']:
        image_url = item['image_url']
        title = item['title']
        image_info = {'url': image_url, 'title': title}
        image_info_list.append(image_info)
    return image_info_list

4.保存图片到本地:

用于保存图片到本地。首先创建一个目录"directory",如果目录不存在的话。然后遍历图片信息列表,依次下载每个图片并保存到目录中,图片的文件名为标题加上".jpg"后缀。

def save_to_images(img_info_list):
    directory = 'images'
    if not os.path.exists(directory):
        os.makedirs(directory)

    for img_info in img_info_list:
        image_url = img_info['url']
        title = img_info['title']
        response = requests.get(image_url)
        with open(os.path.join(directory, f'{title}.jpg'), 'wb') as f:
            f.write(response.content)

【python】爬取斗鱼直播照片保存到本地目录_第1张图片

源码:


#导入了必要的模块requests和os
import requests
import os


# 定义了一个函数get_html(url),
# 用于发送GET请求获取指定URL的响应数据。函数中设置了请求头部信息,
# 以模拟浏览器的请求。函数返回响应数据的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


# 定义了一个函数parse_html(html),
# 用于解析响应数据中的图片信息。通过分析响应数据的结构,
# 提取出每个图片的URL和标题,并将其存储在一个字典中,然后将所有字典组成的列表返回
def parse_html(html):
    rl_list = html['data']['rl']
    # print(rl_list)
    img_info_list = []
    for rl in rl_list:
        img_info = {}
        img_info['img_url'] = rl['rs1']
        img_info['title'] = rl['nn']
        # print(img_url)
        # exit()
        img_info_list.append(img_info)
    # print(img_info_list)
    return img_info_list


# 定义了一个函数save_to_images(img_info_list),用于保存图片到本地。
# 首先创建一个目录"directory",如果目录不存在的话。然后遍历图片信息列表,
# 依次下载每个图片并保存到目录中,图片的文件名为标题加上".jpg"后缀。
def save_to_images(img_info_list):
    dir_path = 'directory'
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    for img_info in img_info_list:
        img_path = os.path.join(dir_path, img_info['title'] + '.jpg')
        res = requests.get(img_info['img_url'])
        res_img = res.content
        with open(img_path, 'wb') as f:
            f.write(res_img)
        # exit()

#在主程序中,设置了要爬取的URL,并调用前面定义的函数来执行爬取、解析和保存操作。
if __name__ == '__main__':
    url = 'https://www.douyu.com/gapi/rknc/directory/yzRec/1'
    html = get_html(url)
    img_info_list = parse_html(html)
    save_to_images(img_info_list)

效果图:

【python】爬取斗鱼直播照片保存到本地目录_第2张图片

        【python】爬取斗鱼直播照片保存到本地目录_第3张图片

给大家推荐一个网站

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


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

   iToday,打开信息的新时代。作为一家创新的IT数字媒体平台,iToday致力于为用户提供最新、最全面的IT资讯和内容。里面包含了技术资讯、IT社区、面试求职、前沿科技等诸多内容。我们的团队由一群热爱创作的开发者和分享的专业编程知识爱好者组成,他们精选并整理出真实可信的信息,确保您获得独特、有价值的阅读体验。随时随地,尽在iToday,与世界保持连接,开启您的信息新旅程!
IT今日热榜 一站式资讯平台IT今日热榜汇聚各类IT热榜:虎嗅、知乎、36氪、京东图书销售、晚点、全天候科技、极客公园、GitHub、掘金、CSDN、哔哩哔哩、51CTO、博客园、GitChat、开发者头条、思否、LeetCode、人人都是产品经理、牛客网、看准、拉勾、Boss直聘icon-default.png?t=N7T8http://itoday.top/#/

你可能感兴趣的:(python,网络爬虫)