python之requests的大全(包括安装,使用及示例)

[python] 2024-04-28 圈点205

摘要:python之requests的大全(包括安装,使用及示例)

Requests 


Python基于urllib,采用 Apache2 Licensed 开源协议的 HTTP 库,能满足 HTTP 测试需求。

Requests 支持 Python3 !



一、安装 Requests

通过pip安装

pip install requests


或者,下载代码后安装:

$ git clone git://github.com/kennethreitz/requests.git

$ cd requests

$ python setup.py install



二、支持的所有方法


requests.get(‘url/json’) #GET请求

requests.post(“url/post”) #POST请求

requests.put(“url/put”) #PUT请求

requests.delete(“url/delete”) #DELETE请求

requests.head(“url/get”) #HEAD请求

requests.options(“url/get”) #OPTIONS请求



三,最简单的使用示例及返回Response对象对应的属性:


import requests

import json


r = requests.get(url='http://www.xoxxoo.com')    # 最基本的GET请求

r = requests.get(url=url, params={'index':'python'})   #带参数的GET请求

requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'})) #POST发送JSON数据


ata = {'some': 'data'}

headers = {'content-type': 'application/json',

           'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}

r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers) #定制header



r.status_code #响应状态码

r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码,返回所有的HTML

r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取

r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩

r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None

#*特殊方法*#

r.json() #Requests中内置的JSON解码器

r.raise_for_status() #失败请求(非200响应)抛出异常

r.encoding #网站编码

r.url





上面的r即为返回的Response对象

使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……

获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码。


r = requests.get('http://www.itwhy.org')

print(r.text, '\n{}\n'.format('*'*79), r.encoding)

r.encoding = 'GBK'

print(r.text, '\n{}\n'.format('*'*79), r.encoding)

 


四,案例之一:


import requests

 

URL = 'http://ip.taobao.com/service/getIpInfo.php'  # 淘宝IP地址库API

try:

    r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1)

    r.raise_for_status()    # 如果响应状态码不是 200,就主动抛出异常

except requests.RequestException as e:

    print(e)

else:

    result = r.json()

    print(type(result), result, sep='\n')



五、使用 Requests 模块上传文件的示例:


import requests

 

url = 'http://127.0.0.1:5000/upload'

files = {'file': open('d:/a/b.png', 'rb')}

#files = {'file': ('report.jpg', open('d:/a/b.png', 'rb'))}     #显式的设置文件名

 

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

print(r.text)


还可以把字符串当着文件进行上传:


import requests

 

url = 'http://127.0.0.1:5000/upload'

files = {'file': ('test.txt', b'Hello Requests.')}     #必需显式的设置文件名

 

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

print(r.text)



六、身份验证

基本身份认证(HTTP Basic Auth):


import requests

from requests.auth import HTTPBasicAuth

 

r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))

# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd'))    # 简写

print(r.json())


另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:


requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))



七、Cookies与会话对象

如果某个响应中包含一些Cookie,你可以快速访问它们:


import requests

 

r = requests.get('http://www.google.com.hk/')

print(r.cookies['NID'])

print(tuple(r.cookies))

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


import requests

 

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

cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}

# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。

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

print(r.json())



会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。

下面就来一个真正的实例,如下是快盘签到脚本:


import requests

 

headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

           'Accept-Encoding': 'gzip, deflate, compress',

           'Accept-Language': 'en-us;q=0.5,en;q=0.3',

           'Cache-Control': 'max-age=0',

           'Connection': 'keep-alive',

           'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}

 

s = requests.Session()

s.headers.update(headers)

# s.auth = ('superuser', '123')

s.get('https://www.kuaipan.cn/account_login.htm')

 

_URL = 'http://www.kuaipan.cn/index.php'

s.post(_URL, params={'ac':'account', 'op':'login'},

       data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'})

r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'})

print(r.json())

s.get(_URL, params={'ac':'common', 'op':'usersign'})



八、超时与异常

timeout 仅对连接过程有效,与响应体的下载无关。


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

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。



九,特殊用法:



r.history  #如何返回(<Response [302]>,)

这里能看出他是使用了302跳转。


>>>r = requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN', allow_redirects = False)

>>>r.status_code

302

只要加上一个参数allow_redirects,禁止了跳转,就直接出现跳转的状态码了



代理访问

采集时为避免被封IP,经常会使用代理。requests也有相应的proxies属性。


import requests


proxies = {

  "http": "http://10.10.1.10:3128",

  "https": "http://10.10.1.10:1080",

}


requests.get("http://www.zhidaow.com", proxies=proxies)


如果代理需要账户和密码,则需这样:


proxies = {

    "http": "http://user:pass@10.10.1.10:3128/",

}


请求头内容

请求头内容可以用r.request.headers来获取。


>>> r.request.headers

{'Accept-Encoding': 'identity, deflate, compress, gzip',

'Accept': '*/*', 'User-Agent': 'python-requests/1.2.3 CPython/2.7.3 Windows/XP'}



持久连接keep-alive

requests的keep-alive是基于urllib3,同一会话内的持久连接完全是自动的。同一会话内的所有请求都会自动使用恰当的连接。

也就是说,你无需任何设置,requests会自动实现keep-alive。



1、官方文档

requests的具体安装过程请看:http://docs.python-requests.org/en/latest/user/install.html#install

requests的官方指南文档:http://docs.python-requests.org/en/latest/user/quickstart.html

requests的高级指南文档:http://docs.python-requests.org/en/latest/user/advanced.html#advanced

requests的文档: http://cn.python-requests.org/en/latest/

python  requests  

感谢反馈,已提交成功,审核后即会显示