Python实现使用request模块下载图片demo示例

不要认为自己比别人做得好,即便你很出色。常问自己,谁对我有恩还没加倍报答。杜绝事必躬亲,学会抓大放小。

本文实例讲述了Python实现使用request模块下载图片。分享给大家供大家参考,具体如下:

利用流传输下载图片

# -*- coding: utf-8 -*-
import requests
def download_image():
  """
  demo:下载图片
  :return:
  """
  headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"}
  url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491366667515&di=8dad3d86740af2c49d3d0461cfd81f63&imgtype=0&src=http%3A%2F%2Fhdn.xnimg.cn%2Fphotos%2Fhdn521%2F20120528%2F1615%2Fh_main_LBxi_2917000000451375.jpg"
  response = requests.get(url, headers=headers, stream=True)
  #print str(response.text).decode('ascii').encode('gbk')
  with open('demo.jpg', 'wb') as fd:
    for chunk in response.iter_content(128):
      fd.write(chunk)
download_image()
def download_image_improved():
  """demo: 下载图片"""
  #伪造headers信息
  headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"}
  #限定URL
  url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491366667515&di=8dad3d86740af2c49d3d0461cfd81f63&imgtype=0&src=http%3A%2F%2Fhdn.xnimg.cn%2Fphotos%2Fhdn521%2F20120528%2F1615%2Fh_main_LBxi_2917000000451375.jpg"
  response = requests.get(url, headers=headers, stream=True)
  from contextlib import closing
  #用完流自动关掉
  with closing(requests.get(url, headers=headers, stream=True)) as response:
    #打开文件
    with open('demo1.jpg', 'wb') as fd:
      #每128写入一次
      for chunk in response.iter_content(128):
        fd.write(chunk)
download_image_improved()

运行结果(在当前目录下下载了一个demo.jpg文件):

希望本文所述对大家Python程序设计有所帮助。

本文Python实现使用request模块下载图片demo示例到此结束。在我们的记忆中,每一次“错过”都是完美的:或是浪漫的情感历程,或是平步青云的官运,或是唾手可得的财气。但同时,我们也许错过了疾病,错过了灾难,错过了失败,错过了与己无益的是与非。所以,不必为错过叹息,因为在叹息中,我们又将错过今日的完美。小编再次感谢大家对我们的支持!

标签: 下载图片 Python