您的位置:首页 > 编程语言 > Python开发

python:利用requests库下载图片

2018-02-21 21:05 197 查看
今天非常兴奋,身为python小白的我经过数天的看视频和看书,终于看懂了一点

,程序刚刚运行成功。

话不多说,马上分享!

这次用到的是requests库

先来介绍下requests库

Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库

如果你看过上篇文章关于urllib库的使用,你会发现,其实urllib还是非常不方便的,而Requests它会比urllib更加方便,可以节约我们大量的工作。(用了requests之后,你基本都不愿意用urllib了)一句话,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。

默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装

requests的各种请求方式

import requests
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

基本请求requests.get()

import requests
response=requests.get('www.scascac.com')

print('response.text')


这样就相当于我们向网站发送了一个请求,然后打印出来(但是我们想要下载文件不单单要打印,还要把它保存在本地)

with open('meinv.jpg','wb') as f:
f.write(response.content)
f.close()

注意:因为图片是二进制所以不能用response.text (输出的是文本)用requests.content(输出二进制)

一定记得f.close()文件开启了必须关闭!

完整代码如下:

import requests

response=requests.get('http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg')

with open('meinv.jpg','wb') as f:
f.write(response.content)
f.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫