Python实现使用request模块下载图片demo示例
程序员文章站
2023-11-04 10:29:46
本文实例讲述了python实现使用request模块下载图片。分享给大家供大家参考,具体如下:
利用流传输下载图片
# -*- coding: utf-8 -*...
本文实例讲述了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程序设计有所帮助。
推荐阅读