转:python的requests初步使用

上一篇 / 下一篇  2017-03-21 15:39:48 / 个人分类:Python

这里写些简单的使用初步作为一个记录

一、安装 http://cn.python-requests.org/en/latest/user/install.html#install

二、发送无参数的get请求

>>> r = requests.get('http://httpbin.org/get')>>> print r.text {"args": {},"headers": {"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.3.0 CPython/2.6.6 Windows/7","X-Request-Id":"8a28bbea-55cd-460b-bda3-f3427d66b700"},"origin":"124.192.129.84","url":"http://httpbin.org/get"}
三、发送带参数的get请求,将key与value放入一个字典中,通过params参数来传递,其作用相当于urllib.urlencode
>>>importrequests>>>pqyload = {'q':'杨彦星'}>>>r = requests.get('http://www.so.com/s',params = pqyload)>>>r.urlu'http://www.so.com/s?q=%E6%9D%A8%E5%BD%A6%E6%98%9F'

四、发送post请求,通过data参数来传递,
>>> payload = {'a':'杨','b':'hello'}>>> r = requests.post("http://httpbin.org/post", data=payload)>>> print r.text {"args": {},"data":"","files": {},"form": {"a":"\u6768","b":"hello"},"headers": {"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"19","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.3.0 CPython/2.6.6 Windows/7","X-Request-Id":"c81cb937-04b8-4a2d-ba32-04b5c0b3ba98"},"json": null,"origin":"124.192.129.84","url":"http://httpbin.org/post"}>>>

可以看到,post参数已经传到了form里,data不光可以接受字典类型的数据,还可以接受json等格式
>>> payload = {'a':'杨','b':'hello'}>>> import json>>> r = requests.post('http://httpbin.org/post', data=json.dumps(payload))

五、发送文件的post类型,这个相当于向网站上传一张图片,文档等操作,这时要使用files参数
>>> url ='http://httpbin.org/post'>>> files = {'file': open('touxiang.png','rb')}>>> r = requests.post(url, files=files)

5.1 定制headers,使用headers参数来传递
>>> import json>>> url ='https://api.github.com/some/endpoint'>>> payload = {'some':'data'}>>> headers = {'content-type':'application/json'}>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

六、响应内容

6.1 响应状态码

r= requests.get('http://httpbin.org/get')
printr.status_code
6.2响应头

>>>printr.headers
{'content-length':'519','server':'gunicorn/18.0','connection':'keep-alive','date':'Sun, 15 Jun 2014 14:19:52 GMT','access-control-allow-origin':'*','content-type':'application/json'}

也可以取到这个个别的响应头用来做一些判断,这里的参数是不区分大小写的

r.headers[‘Content-Type’]

r.headers.get(‘Content-Type’)

6.3 响应内容,前面已经在应用了

r.text

r.content

 

七、获取响应中的cookies

>>> r = requests.get('http://www.baidu.com')>>> r.cookies['BAIDUID']'D5810267346AEFB0F25CB0D6D0E043E6:FG=1'

也可以自已定义请求的COOKIES
>>> url ='http://httpbin.org/cookies'>>> cookies = {'cookies_are':'working'}>>> r = requests.get(url,cookies = cookies)>>> >>> print r.text {"cookies"

TAG: Python python

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar