例子。
@@ -0,0 +1,22 @@
+__author__ = 'tanteng'
+
+import requests
+
+def testrequests():
+
+ url = 'http://www.x.com/index/pyrequests'
+
+ params = {
+ 'x':'xxxx',
+ 'y':'yyyy'
+ }
+
+ re = requests.get(url,params)
+
+ return re
+
+
+if __name__ == '__main__':
+ re = testrequests()
+ print(re.text)
+
简单的例子:
想象下我们试图使用get方法从http://example.test/获取资源并且查看返回代码,content-type头信息,还有response的主体内容。这件事无论使用urllib2 或者Requests都是很容易实现的。
urllib2
>>> import urllib2
>>> url = 'http://example.test/'
>>> response = urllib2.urlopen(url)
>>> response.getcode()
200
>>> response.headers.getheader('content-type')
'text/html; charset=utf-8'
>>> response.read()
'Hello, world!'
Requests
>>> import requests
>>> url = 'http://example.test/'
>>> response = requests.get(url)
>>> response.status_code
200
>>> response.headers['content-type']
'text/html; charset=utf-8'
>>> response.content
u'Hello, world!'
这两种方法很相似,相对于urllib2调用方法读取response中的属性信息,Requests则是使用属性名来获取对应的属性值。
两者还有两个细微但是很重要的差别:
1 Requests 自动的把返回信息有Unicode解码
2 Requests 自动保存了返回内容,所以你可以读取多次,而不像urllib2.urlopen()那样返回的只是一个类似文件类型只能读取一次的对象。
第二点是在python交互式环境下操作代码很令人讨厌的事情
发送带参数的get请求,将key与value放入一个字典中,通过params参数来传递,其作用相当于urllib.urlencode
>>> import requests
>>> pqyload = {'q':'杨彦星'}
>>> r = requests.get('http://www.so.com/s',params = pqyload)
>>> r.url
u'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)