您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關怎么在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中使用request模塊下載圖片有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。