Requests模块使用,看这篇就够了!
Requests模块是一个用于网络访问的模块,其实有很多类似的模块,比如urlib,urllib2,httplib,httplib2,它们基本上提供类似的功能,那么为什么requests模块可以被引出呢?打开它的官方网站,看看它是一个“人类”使用的http模块。那么,它是如何人性化的呢?我相信,如果你以前使用过urlib等模块,你会发现它真的很人性化。
一、导入
下载后,导入模块非常简单,代码如下:
importrequests
二、请求url
在这里,我们列出了最常见的语法来发送get或post请求。
1.发送无参数get请求:
r=requests.get("http://pythontab.com/justTest")
现在,我们得到了一个响应对象r,我们可以利用这个对象得到我们想要的任何信息。
在上面的例子中,get请求没有任何参数,如果需要参数怎么办?
2.发送带参数的get请求
payload={'key1':'value1','key2':'value2'} r=requests.get("http://pythontab.com/justTest",params=payload)
据了解,我们的get参数是通过params关键字参数传递的。
我们可以打印请求的具体url,看看它是否正确:
>>>printr.url http://pythontab.com/justTest?key2=value2&key1=value
可以看出,确实访问了正确的url。
还可以向一个请求参数传递一个列表:
>>>payload={'key1':'value1','key2':['value2','value3']} >>>r=requests.get("http://pythontab.com/justTest",params=payload) >>>printr.url http://pythontab.com/justTest?key1=value&key2=value2&key2=value3
以上是get请求的基本形式。
3.发送post请求
r=requests.post("http://pythontab.com/postTest",data={"key":"value"})
据了解,post请求参数是通过data关键字参数传递的。
现在data参数传递字典,我们也可以传递json格式的数据,如下:
>>>importjson >>>importrequests >>>payload={"key":"value"} >>>r=requests.post("http://pythontab.com/postTest",data=json.dumps(payload))
因为发送json格式数据太常见了,所以在Requests模块的高版本中,添加了关键字参数json,可以直接将json数据发送到post请求,而无需使用json模块,请参见:
>>>payload={"key":"value"} >>>r=requests.post("http://pythontab.com/postTest",json=payload)
如果我们想post文件怎么办?此时需要使用files参数:
>>>url='http://pythontab.com/postTest' >>>files={'file':open('report.xls','rb')} >>>r=requests.post(url,files=files) >>>r.text
在post文件中,我们还可以指定文件名等额外信息:
>>>url='http://pythontab.com/postTest' >>>files={'file':('report.xls',open('report.xls','rb'),'application/vnd.ms-excel',{'Expires':'0'})} >>>r=requests.post(url,files=files)
tips:强烈建议使用二进制模式打开文件,因为如果文本文件格式打开,可能是因为“Content-Length“这个header出错了。
可见,使用Requests发送请求很简单!
三、获取返回信息
让我们来看看发送请求后如何获取返回信息。我们继续使用上面的例子:
>>>importrequests >>>r=requests.get('http://pythontab.com/justTest') >>>r.text
r.text输出的编码格式是什么?
>>>r.encoding 'utf-8'
它以utf-8格式输出。如果我想改变rtf-8格式.text的输出格式呢?
>>>r.encoding='ISO-8859-1'
这样,输出格式将被改为“”ISO-8859-1”了。
还有一个输出语句叫r.content,所以这个和r.text有什么区别?r.content返回字节流。如果我们要求图片地址并保存图片,我们可以使用它。这里的代码片段如下:
defsaveImage(imgUrl,imgName="default.jpg"): r=requests.get(imgUrl,stream=True) image=r.content destDir="D:\" print("保存图片"+destDir+imgName+"\n") try: withopen(destDir+imgName,"wb")asjpg: jpg.write(image) return exceptIOError: print("IOError") return finally: jpg.close
刚才介绍的r.text返回字符串,所以,如果要求的响应是json,我能直接得到json格式的数据吗?r.json()就是为此准备的。
我们还可以使用r获取服务器返回的原始数据.raw.read()没关系。但是,如果你真的想得到原始的返回数据,请记得在请求中添加“stream=True“选项,如:
r=requests.get('https://api.github.com/events',stream=True)。
还可以获得响应状态码:
>>>r=requests.get('http://pythontab.com/justTest') >>>r.status_code 200
也可以使用requeststsstsss.codes.ok指的是200的返回值:
>>>r.status_code==requests.codes.ok True
四、关于headers
可打印响应头:
>>>r=requests.get("http://pythontab.com/justTest") >>>r.headers `r.headers`例如,一个字典被返回: { 'content-encoding':'gzip', 'transfer-encoding':'chunked', 'connection':'close', 'server':'nginx/1.0.4', 'x-runtime':'147ms', 'etag':'"e1ca502697e5c93773dc0767"', 'content-type':'application/json' }
我们可以用以下方法来判断一些响应头:
r.headers['Content-Type']
或者
r.headers.get('Content-Type')
如果我们想得到请求头(即我们向服务器发送的头部信息),我们该怎么办?r可以使用.request.直接获得headers。
同时,我们还可以在要求数据时添加自定义的headers(通过headers关键字参数传输):
>>>headers={'user-agent':'myagent'} >>>r=requests.get("http://pythontab.com/justTest",headers=headers)
五、关于Cookiess
如果一个响应包含cookies,我们可以使用以下方法来获得它们:
>>>url='http://www.pythontab.com' >>>r=requests.get(url) >>>r.cookies['example_cookie_name'] 'example_cookie_value'
也可以发送自己的cookie(使用cookies关键字参数):
>>>url='http://pythontab.com/cookies' >>>cookies={'cookies_are':'working'} >>>r=requests.get(url,cookies=cookies)
六、关于重定向
有时,当我们要求url时,服务器会自动重定向我们的请求。例如,github将我们的http请求重定向为https请求。我们可以使用r.history查看重定向:
>>>r=requests.get('http://pythontab.com/') >>>r.url 'http://pythontab.com/' >>>r.history []
从上面的例子可以看出,我们使用http协议访问,结果是r.在url中,打印的是https协议。如果非要服务器使用http协议,即禁止服务器自动重定向,该怎么办?使用allow_redirects 参数:
r=requests.get('http://pythontab.com',allow_redirects=False)
七、关于请求时间
我们可以使用timeout参数来设置url请求超时间(时间单位为秒):
requests.get('http://pythontab.com',timeout=1)
八、关于代理
还可以在程序中指定代理进行http或https访问(使用proxies关键字参数),如下:
proxies={ "http":"http://10.10.1.10:3128", "https":"http://10.10.1.10:1080", } requests.get("http://pythontab.com",proxies=proxies)
九、关于sesssion
我们有时会有这样的情况,我们需要登录一个网站,然后要求相关的url,然后我们可以使用session,我们可以使用网站登录应用程序登录,然后得到session,最后可以使用session要求其他url:
s=requests.Session() login_data={'form_email':'youremail@example.com','form_password':'yourpassword'} s.post("http://pythontab.com/testLogin",login_data) r=s.get('http://pythontab.com/notification/') printr.text
其中,form_email和form_password是豆瓣登录框相应元素的name值。
十、下载页面
还可以使用Requests模块下载网页,代码如下:
r=requests.get("http://www.pythontab.com") withopen("haha.html","wb")ashtml: html.write(r.content) html.close()