Requests

一、中文官方网址:http://cn.python-requests.org/zh_CN/latest/

二、官方描述:Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。

三、Windows下安装requests:pip install requests

四、快速上手

参考:http://cn.python-requests.org/zh_CN/latest/user/quickstart.html

1、发送请求:

import requests#导入 Requests 模块

r1=requests.get('https://api.github.com/events')#返回r的Response对象,get请求

r2=requests.post('http://httpbin.org/post',data={'key':'value'})#post请求

r3=requests.put('http://httpbin.org/put',data={'key':'value'})#put请求

r4=requests.delete('http://httpbin.org/delete')#delete请求

r5=requests.head('http://httpbin.org/get')#head请求

r6=requests.options('http://httpbin.org/get')#options请求

2、传递 URL 参数:Requests 允许你使用params关键字参数,以一个字符串字典来提供这些参数。

url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm'

#淘宝查询电话号码归属地(可用)

response1 = requests.get(url)

payload = {'tel': '181****8377'}#输入具体的手机号码

response2 = requests.get(url, params=payload)

print(response1)

print(response2)

print(response2.url)

图1

3、响应内容:Requests 会自动解码来自服务器的内容,大多数 unicode 字符集都能被无缝地解码。

print('二进制响应内容:',response2.content)#二进制响应内容

print('响应内容',response2.text)#响应内容,用这个,

#请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。

# print('json响应内容',response2.json())#json响应内容,如果 JSON 解码失败, r.json() 就会抛出一个异常。

print('文本编码',response2.encoding)#GBK

# response2.encoding = 'utf-8'

# print(response2.encoding)#'utf-8'

response3 = requests.get(url, params=payload,stream=True)

print('原始响应内容',response3.raw)#原始响应内容,获取来自服务器的原始套接字响应

filename ='filename'#将文本流保存到文件

with open(filename, 'wb') as fd:

    for chunk in response3.iter_content():

        fd.write(chunk)

4、定制请求头:如果你想为请求添加 HTTP 头部,只要简单地传递一个dict给headers参数就可以了。

headers = {'user-agent': 'my-app/0.0.1'}

response4 = requests.get(url, headers=headers)

print('定制请求头',response4.headers)#注意: 定制 header 的优先级低于某些特定的信息源

5、复杂的 POST 请求

5.1、通常,你想要发送一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给data参数。你的数据字典在发出请求时会自动编码为表单形式:

>>> payload={'key1':'value1','key2':'value2'}

>>> r=requests.post("http://httpbin.org/post",data=payload)>>>

print(r.text)

#{ ... "form":{ "key2": "value2","key1": "value1" },...}

5.2、你还可以为data参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:

>>> payload=(('key1','value1'),('key1','value2'))

>>> r=requests.post('http://httpbin.org/post',data=payload)

>>> print(r.text)

#{ ... "form": {"key1": [ "value1", "value2" ] },...}

5.3、很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个string而不是一个dict,那么数据会被直接发布出去。例如,Github API v3 接受编码为 JSON 的 POST/PATCH 数据:

>>> importjson

>>> url='https://api.github.com/some/endpoint'

>>> payload={'some':'data'}

>>> r=requests.post(url,data=json.dumps(payload))

此处除了可以自行对dict进行编码,你还可以使用json参数直接传递,然后它就会被自动编码。这是 2.4.2 版的新加功能:

>>> url='https://api.github.com/some/endpoint'

>>> payload={'some':'data'}

>>> r=requests.post(url,json=payload)

6、POST一个多部分编码(Multipart-Encoded)的文件

>>> url='http://httpbin.org/post'

>>> files={'file':open('report.xls','rb')}

>>> r=requests.post(url,files=files)

>>> r.text

#{ ... "files": {"file": "" },...}

7、响应状态码:.status_code

print('响应码:',response2.status_code)#200

# print(requests.codes.ok)#200,内置的状态码查询对象

print(response2.raise_for_status())#None

#如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),

#我们可以通过 Response.raise_for_status() 来抛出异常,无异常就是None.

bad_r = requests.get('http://httpbin.org/status/404')

print(bad_r.status_code)#404

bad_r.raise_for_status()#requests.exceptions.HTTPError: 404 Client Error: NOT FOUND for url: http://httpbin.org/status/404

8、响应头:HTTP 头部是大小写不敏感的。

print(response2.headers['Content-Type'])

print(response2.headers.get('content-type'))

图2

9、Cookie:

9.1、Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似,但接口更为完整,适合跨域名跨路径使用。

print(response2.cookies)

print(response2.cookies['cookie2'])

图3

9.2、要想发送你的cookies到服务器,可以使用cookies参数:

>>> url='http://httpbin.org/cookies'

>>> cookies=dict(cookies_are='working')

>>> r=requests.get(url,cookies=cookies)

>>> r.text'

#{"cookies": {"cookies_are": "working"}}'

>>> jar=requests.cookies.RequestsCookieJar()

>>> jar.set('tasty_cookie','yum',domain='httpbin.org',path='/cookies')

>>> jar.set('gross_cookie','blech',domain='httpbin.org',path='/elsewhere')

>>> url='http://httpbin.org/cookies'

>>> r=requests.get(url,cookies=jar)

>>> r.text'

#{"cookies": {"tasty_cookie": "yum"}}'

10、重定向与请求历史:默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的history方法来追踪重定向。Response.history是一个Response对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

例如,Github 将所有的 HTTP 请求重定向到 HTTPS:

>>> r=requests.get('http://github.com')

>>> r.url'https://github.com/'

>>> r.status_code200

>>> r.history

#[]

10.1、如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过allow_redirects参数禁用重定向处理:

>>> r=requests.get('http://github.com',allow_redirects=False)

>>> r.status_code#301

>>> r.history#[]

10.2、如果你使用了 HEAD,你也可以启用重定向:

>>> r=requests.head('http://github.com',allow_redirects=True)

>>> r.url'https://github.com/'

>>> r.history#[]

11、超时:你可以告诉 requests 在经过以timeout参数设定的秒数时间之后停止等待响应。

requests.get('http://github.com',timeout=0.001)

12、错误与异常

12.1、遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个ConnectionError异常。

12.2、如果 HTTP 请求返回了不成功的状态码,Response.raise_for_status()会抛出一个HTTPError异常。

12.3、若请求超时,则抛出一个Timeout异常。

12.4、若请求超过了设定的最大重定向次数,则会抛出一个TooManyRedirects异常。

12.5、所有Requests显式抛出的异常都继承自requests.exceptions.RequestException。

更多高级用法参考:http://cn.python-requests.org/zh_CN/latest/user/advanced.html#advanced

你可能感兴趣的:(Requests)