python使用requests库下载单张图片的简单示例

python使用requests库下载单张图片的简单示例

  • 简要说明
  • 代码示例

简要说明

下载图片的核心代码如下:

res = requests.get(url=img_url, headers=headers)
if 200 == res.status_code:
    with open(file_path, 'wb') as file:
        file.write(res.content)

使用requests库,直接对图片的url进行请求,如果返回状态码为200(ok)的话,那么get方法返回的content二进制串即为图片的真实内容,我们只需将其写入文件即可。

代码示例

下面的示例代码中加入了路径的处理。

import requests
import random
import os

class PicDownloader():
    def __init__(self):
        self.count = 0          # 用于文件编号
        self.file_name = 'img'  # 默认文件名
        self.working_dir = '.'  # 默认工作目录
    
    def download_img(self, img_url, dir='.'):
        '''
        下载url指定的图片到本地dir目录
        '''
        self.count += 1
        self.file_name = self.file_name + '_' + str(self.count) + '.jpg'

        # 如果指定的下载目录不存在,则尝试创建
        if os.path.isdir(dir):
            self.working_dir = dir
        else:
            try:
                os.makedirs(dir)
                self.working_dir = dir
            except OSError as e:
                print(f'create dir: {dir} failed')
        
        # 生成完整的路径名
        file_path = os.path.join(self.working_dir, self.file_name)

        print(f'开始下载文件:{file_path}')
        headers = self.get_headers()
        try:
            res = requests.get(url=img_url, headers=headers)
            if 200 == res.status_code:
                with open(file_path, 'wb') as file:
                    file.write(res.content)
        except Exception as e:
            print(f'下载文件失败: {file_path}')
            print(repr(e))
        print('文件下载成功')
        
    # 供爬虫使用的,此例中并不需要这么多,随便取一种就行了
    def get_headers(self):
        user_agent_list = [
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
            "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
            "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"]

        userAgent = random.choice(user_agent_list)
        headers = {'User-Agent': userAgent}
        return headers


if __name__== '__main__':
    downloader = PicDownloader()
    downloader.download_img('https://images.weserv.nl/?url=https%3A%2F%2F23img.com%2Fi%2F2022%2F08%2F17%2Fqykvvx.jpg', 'd:/test')

效果如下:

python使用requests库下载单张图片的简单示例_第1张图片

你可能感兴趣的:(Python应用,爬虫基础,python,爬虫,开发语言)