Python爬取图片并保存

2024-06-11阅读数:480
上一篇:Python读写文本文件
下一篇:Python解析Json字符串
# coding=utf-8
import requests

# 请求远程图片的函数,参数url为图片的完整链接,函数返回请求回来的二进制内容
def get_content(url):
    # 准备好User-Agent到变量myheaders
    myheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36'}

    response = requests.get(url, headers=myheaders) #把上面准备好的User-Agent变量赋值给requests.get的headers参数 
    status_code = response.status_code 
    if status_code != 200:
        print(f'request failed: {status_code}')
        return ''

    return response.content

# 保存图片
def save_image(file_name, img_data):
    with open(file_name, 'wb') as img:
        img.write(img_data)


if __name__ == '__main__':
    url = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
    content = get_content(url)

    # 从url中提取文件名
    file_name = url.split('/')[-1]
    save_image(file_name, content)