Python第三方库Requests学习

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())

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。