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

yipeiwu_com6年前Python基础

本文实例讲述了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函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

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

相关文章

对pandas写入读取h5文件的方法详解

1、引言 通过参考相关博客对hdf5格式简要介绍。 hdf5在存储的是支持压缩,使用的方式是blosc,这个是速度最快的也是pandas默认支持的。 使用压缩可以提磁盘利用率,节省空间。...

python 对txt中每行内容进行批量替换的方法

python 对txt中每行内容进行批量替换的方法

如下所示: f = open('./val.txt') lines = f.readlines() #整行读取 f.close() for line in lines: rs =...

Python数据结构与算法之图的最短路径(Dijkstra算法)完整实例

Python数据结构与算法之图的最短路径(Dijkstra算法)完整实例

本文实例讲述了Python数据结构与算法之图的最短路径(Dijkstra算法)。分享给大家供大家参考,具体如下: # coding:utf-8 # Dijkstra算法——通过边实现...

Python将DataFrame的某一列作为index的方法

下面代码实现了将df中的column列作为index df.set_index(["Column"], inplace=True) 以上这篇Python将DataFrame的某一...

python正则分组的应用

复制代码 代码如下:import retext='V101_renow.Android.2.2.Normal.1.Alpha.apk?IMSI=460029353813976&MOBIL...