使用requests库爬取网络图片、视频、音乐并存储

使用网络爬虫获取网络图片并存储

import requests
import os
import uuid


def download_and_store_image(url):
    try:
        # 根据目录
        root = "/home/wong/Desktop/images/"
        # 文件名
        path = root + str(uuid.uuid4())+".jpg"
        # 根目录不存创建根目录
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            r = requests.get(url)
            r.raise_for_status()
            with open(path, "wb") as f:
                # r.content获取的是二进制形式的内容,把二进制数据写入文件
                f.write(r.content)
                f.close()
                print("文件保存成功")
    except:
        print("文件保存失败")


if __name__ == "__main__":
    url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1563543616448&di=7c0d25c3737d437cc457efaa4ae1ca82&imgtype=0&src=http%3A%2F%2Fwww.chinadaily.com.cn%2Fculture%2Fart%2Fimg%2Fattachement%2Fjpg%2Fsite181%2F20150529%2F180373cf843216d2ffe52f.jpg"
    download_and_store_image(url)

使用网络爬虫获取网络视频并存储

import requests
import os
import uuid


def download_and_store_image(url):
    try:
        # 根据目录
        root = "/home/wong/Desktop/videos/"
        # 文件名
        path = root + str(uuid.uuid4())+".mp4"
        # 根目录不存创建根目录
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            r = requests.get(url)
            r.raise_for_status()
            with open(path, "wb") as f:
                # r.content获取的是二进制形式的内容,把二进制数据写入文件
                f.write(r.content)
                f.close()
                print("文件保存成功")
    except:
        print("文件保存失败")


if __name__ == "__main__":
    url = "http://111.231.191.26/See%20You%20Again.mp4"
    download_and_store_image(url)

使用网络爬虫获取网络音乐并存储

import requests
import os
import uuid


def download_and_store_image(url):
    try:
        # 根据目录
        root = "/home/wong/Desktop/music/"
        # 文件名
        path = root + str(uuid.uuid4())+".mp3"
        # 根目录不存创建根目录
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            r = requests.get(url)
            r.raise_for_status()
            with open(path, "wb") as f:
                # r.content获取的是二进制形式的内容,把二进制数据写入文件
                f.write(r.content)
                f.close()
                print("文件保存成功")
    except:
        print("文件保存失败")


if __name__ == "__main__":
    url = "https://webfs.yun.kugou.com/201907191936/21ad09311b751436c5612c86358dbc58/G162/M0B/0C/01/gpQEAFzQ_H6AUcGxADW6o5XaYZU550.mp3"
    download_and_store_image(url)

你可能感兴趣的:(Python,reuqests,爬虫,音乐,视频,图片)