python中Requests请求的安装与常见用法

 更新时间:2022年07月07日 09:58:49   作者:你是猴子请来的救兵吗!!  
Requests是一常用的http请求库,它使用python语言编写,可以方便地发送http请求,以及方便地处理响应结果,下面这篇文章主要给大家介绍了关于python中Requests请求的安装与常见用法的相关资料,需要的朋友可以参考下

一、requests

request的说法网上有很多,简单来说就是就是python里的很强大的类库,可以帮助你发很多的网络请求,比如get,post,put,delete等等,这里最常见的应该就是get和post

二、requests安装方式

$ pip install requests
$ easy_install requests

三、说说常见的两种请求,get和post

1、get请求

(1)参数直接跟在url后面,即url的“ ?”后面,以key=value&key=value的形式

(2)由于get的参数是暴露在外面的,所以一般不传什么敏感信息,经常用于查询等操作

(3)由于参数是跟在url后面的,所以上传的数据量不大

2、post请求

(1)参数可以写在url后面,也可以写在body里面

(2)用body上传请求数据,上传的数据量比get大

(3)由于写在body体里,相对安全

post正文格式

(1)form表单  html提交数据的默认格式

                          Content-Type: application/x-www-form-urlencoded

                          例如: username=admin&password123

  (2) multipart-form-data . 复合表单 可转数据+文件

(3)纯文本格式 raw ,最常见的 json . xml html js

        Content-Type:application/json . text/xml . text/html

   (4) binary . 二进制格式:只能上传一个文件

四、requests发送请求

1、requests发送get请求

url = "http://www.search:9001/search/"
param = {"key":"你好"}
res = requests.get(url=url, params=params)

2、request发送post请求 (body是json格式,如果还带cookie)

headers = {'Content-Type': 'application/json'} #必须有
url = "http://www.search:9001/search/"
data= {"key":"你好"}
cookies = {"uid":"1"}
res = requests.post(url=url, headers=headers, data=data, cookies=cookies)

3、 request发送post请求 (body是urlencoded格式)

url = "http://www.search:9001/search/"
data= {"key":"你好"}

res = requests.post(url=url, headers=headers)

4、 request上传文件

def post_file_request(url, file_path):
    if os.path.exists(file_path):
        if url not in [None, ""]:
            if url.startswith("http") or url.startswith("https"):
                files = {'file': open(file_path, 'rb')}
                res = requests.post(url, files=files, data=data)
                return {"code": 0, "res": res}
            else:
                return {"code": 1, "res": "url格式不正确"}
        else:
            return {"code": 1, "res": "url不能为空"}
    else:
        return {"code": 1, "res": "文件路径不存在"}

五、response

request发送请求后,会返回一个response,response里有好多信息,我进行了一下封装,基本如下

 @staticmethod
    def get_response_text(response):
        if response not in [None, ""]:
            if isinstance(response, requests.models.Response):
                return {"code": 0, "res": response.text.encode('utf-8').decode('unicode_escape')}  #这种方式可以将url编码转成中文,返回响应文本
            else:
                return {"code": 1, "res": "response不合法"}
        else:
            return {"code": 1, "res": "response对像不能为空"}
 
    @staticmethod
    def get_response_status_code(response):
        if response not in [None, ""]:
            if isinstance(response, requests.models.Response):
                return {"code": 0, "res": response.status_code} #返回响应状态吗
            else:
                return {"code": 1, "res": "response不合法"}
        else:
            return {"code": 1, "res": "response对像不能为空"}
 
    @staticmethod
    def get_response_cookies(response):
        if response not in [None, ""]:
            if isinstance(response, requests.models.Response):
                return {"code": 0, "res": response.cookies} #返回cookies
            else:
                return {"code": 1, "res": "response不合法"}
        else:
            return {"code": 1, "res": "response对像不能为空"}
 
    @staticmethod
    def get_response_headers(response):
        if response not in [None, ""]:
            if isinstance(response, requests.models.Response):
                return {"code": 0, "res": response.headers} #返回headers
            else:
                return {"code": 1, "res": "response不合法"}
        else:
            return {"code": 1, "res": "response对像不能为空"}
 
    @staticmethod
    def get_response_encoding(response):
        if response not in [None, ""]:
            if isinstance(response, requests.models.Response):
                return {"code": 0, "res": response.encoding} #返回编码格式
            else:
                return {"code": 1, "res": "response不合法"}
        else:
            return {"code": 1, "res": "response对像不能为空"}

补充:requests中遇到问题

获取cookie

# -*- coding:utf-8 -*-
#获取cookie
import requests
import json

url = "https://www.baidu.com/"
r = requests.get(url)

#将RequestsCookieJar转换成字典
c = requests.utils.dict_from_cookiejar(r.cookies)
print(r.cookies)
print(c)

for a in r.cookies:
    print(a.name,a.value)

>> 控制台输出:
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
{'BDORZ': '27315'}
BDORZ 27315

发送Cookie

# -*- coding:utf-8 -*-
#发送cookie到服务器
import requests
import json

host = "*****"
endpoint = "cookies"

url = ''.join([host,endpoint])
#方法一:简单发送
# cookies = {"aaa":"bbb"}
# r = requests.get(url,cookies=cookies)
# print r.text

#方法二:复杂发送
s = requests.session()
c = requests.cookies.RequestsCookieJar()
c.set('c-name','c-value',path='/xxx/uuu',domain='.test.com')
s.cookies.update(c) 

总结

到此这篇关于python中Requests请求的安装与常见用法的文章就介绍到这了,更多相关python中Requests请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 利用python3如何给数据添加高斯噪声

    利用python3如何给数据添加高斯噪声

    高斯噪声既是符合高斯正态分布的误差,一些情况下我们需要向标准数据中加入合适的高斯噪声会让数据变得有一定误差而具有实验价值,下面这篇文章主要给大家介绍了关于利用python3如何给数据添加高斯噪声的相关资料,需要的朋友可以参考下
    2022-03-03
  • Python实现的彩票机选器实例

    Python实现的彩票机选器实例

    这篇文章主要介绍了Python实现彩票机选器的方法,可以模拟彩票号码的随机生成功能,需要的朋友可以参考下
    2015-06-06
  • python的dataframe和matrix的互换方法

    python的dataframe和matrix的互换方法

    下面小编就为大家分享一篇python的dataframe和matrix的互换方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04
  • Python处理PDF及生成多层PDF实例代码

    Python处理PDF及生成多层PDF实例代码

    Python提供了众多的PDF支持库,本篇文章主要介绍了Python处理PDF及生成多层PDF实例代码,这样就能够实现图片扫描上来的内容也可以进行内容搜索的目标
    2017-04-04
  • matplotlib之Pyplot模块绘制三维散点图使用颜色表示数值大小

    matplotlib之Pyplot模块绘制三维散点图使用颜色表示数值大小

    在撰写论文时常常会用到matplotlib来绘制三维散点图,下面这篇文章主要给大家介绍了关于matplotlib之Pyplot模块绘制三维散点图使用颜色表示数值大小的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • 对Keras自带Loss Function的深入研究

    对Keras自带Loss Function的深入研究

    这篇文章主要介绍了对Keras自带Loss Function的深入研究,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • Python如何使用cv2.canny进行图像边缘检测

    Python如何使用cv2.canny进行图像边缘检测

    这篇文章主要介绍了Python如何使用cv2.canny进行图像边缘检测问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • 浅析Python中线程以及线程阻塞

    浅析Python中线程以及线程阻塞

    这篇文章主要为大家简单介绍一下Python中线程以及线程阻塞的相关知识,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下
    2023-04-04
  • 浅谈matplotlib.pyplot与axes的关系

    浅谈matplotlib.pyplot与axes的关系

    这篇文章主要介绍了浅谈matplotlib.pyplot与axes的关系,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • Python 复平面绘图实例

    Python 复平面绘图实例

    今天小编就为大家分享一篇Python 复平面绘图实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11

最新评论