码迷,mamicode.com
首页 > 编程语言 > 详细

Python第三方库Requests学习

时间:2014-11-02 20:59:08      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   sp   数据   

1.安装

1 git clone git://github.com/kennethreitz/requests.git
2 cd requests
3 python setup.py install

2.上点威力

(GET)

1 >>> import requests
2 >>> url = http://dict.baidu.com/s
3 >>> payload = {wd:python}
4 >>> r = requests.get(url,params=payload)  //最基本带参数的get请求
5 <Response [200]>
6 >>> print(r.url)
7 http://dict.baidu.com/s?wd=python
8 >>> print(r.text)  //解码后的数据

(POST)

1 >>> import requests
2 >>> import json
3 >>> r = requests.post(https://api.github.com/some/endpoint, data=json.dumps({some: data}))
4 >>> print (r.json())
5 {udocumentation_url: uhttps://developer.github.com/v3, umessage: uNot Found}

定制Header

 1 >>> import requests
 2 >>> import json
 3 >>> data = {some:data}
 4 >>> headers = {content-type:application/json,User-Agent:Mozilla/5.0(x84_64;)Firefox/22.0}
 5 >>> r = requests.post(https://api.github.com/some/endpoint,data=data,headers=headers)
 6 >>> print(r.text)
 7 {
 8   "message": "Not Found",
 9   "documentation_url": "https://developer.github.com/v3"
10 }

超时设置

1 requests.get(http://github.com, timeout=0.001)
2 
3 ----------------------
4 一堆异常,重点看后面
5 ConnectTimeout: HTTPConnectionPool(host=github.com, port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.HTTPConnection object at 0x01EAE6F0>, Connection to github.com timed out. (connect timeout=0.001)))

访问Cookie

1 import requests
2 r = requests.get(http://www.google.com.hk/)
3 print(r.cookies[NID])
4 print(tuple(r.cookies))

也可以往服务器发送Cookie

1 import requests
2 url = http://myserver.org/cookies
3 cookies = {testCookies_1: Hello_Python3, testCookies_2: Hello_Requests}
4 # 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。
5 r = requests.get(url, cookies=cookies)
6 print(r.json())

 

Python第三方库Requests学习

标签:style   blog   http   io   color   ar   os   sp   数据   

原文地址:http://www.cnblogs.com/sxmcACM/p/4069871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!