欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)使用request模塊下載圖片demo示例

 更新時(shí)間:2019年05月24日 11:51:19   作者:TKtalk  
這篇文章主要介紹了Python實(shí)現(xiàn)使用request模塊下載圖片,結(jié)合完整實(shí)例形式分析了Python基于requests模塊的流傳輸文件下載操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)使用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
  #用完流自動(dòng)關(guān)掉
  with closing(requests.get(url, headers=headers, stream=True)) as response:
    #打開(kāi)文件
    with open('demo1.jpg', 'wb') as fd:
      #每128寫(xiě)入一次
      for chunk in response.iter_content(128):
        fd.write(chunk)
download_image_improved()

運(yùn)行結(jié)果(在當(dāng)前目錄下下載了一個(gè)demo.jpg文件):

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門(mén)與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論