首页 > 代码库 > Python第三方库Requests学习

Python第三方库Requests学习

1.安装

1 git clone git://github.com/kennethreitz/requests.git2 cd requests3 python setup.py install

2.上点威力

(GET)

1 >>> import requests2 >>> url = http://dict.baidu.com/s3 >>> 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=python8 >>> print(r.text)  //解码后的数据

(POST)

1 >>> import requests2 >>> import json3 >>> r = requests.post(https://api.github.com/some/endpoint, data=http://www.mamicode.com/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 = http://www.mamicode.com/{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=http://www.mamicode.com/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 requests2 r = requests.get(http://www.google.com.hk/)3 print(r.cookies[NID])4 print(tuple(r.cookies))

也可以往服务器发送Cookie

1 import requests2 url = http://myserver.org/cookies3 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学习