在python的世界里,有很多库被设计用来发起http访问。
以下列举常用的方法:
- urllib,有urlencode方法,在urllib2中没有
- urllib2,可以接受Request对象,可以伪装agent,但是urllib不行
- urllib3,还没研究过
- httplib, 据说是urllib是在这个上面封装的
- httplib2
- requests
据说以上最好用的还是Requests,Requests使用文档 传送门
talk is cheap,show me the code!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import requests resp = requests.get('http://www.badu.com')
dict = resp.json()
text = resp.text
s = requests.Session() s.get('http://httpbin.org/get')
payload = {'key1': 'value1', 'key2': ['value2', 'value3']} r = requests.get('http://httpbin.org/get', params=payload) print(r.url)
payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", data=payload) print(r.text)
madminyload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", json=payload) print(r.text)
|