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请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python argparse模块应用实例解析

    Python argparse模块应用实例解析

    这篇文章主要介绍了Python argparse模块应用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • python实现记事本功能

    python实现记事本功能

    这篇文章主要为大家详细介绍了python实现记事本功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • python3.4下django集成使用xadmin后台的方法

    python3.4下django集成使用xadmin后台的方法

    本篇文章主要介绍了python3.4下django集成使用xadmin后台的方法,具有一定的参加价值,有兴趣的可以了解一下
    2017-08-08
  • Python GUI编程 文本弹窗的实例

    Python GUI编程 文本弹窗的实例

    今天小编就为大家分享一篇Python GUI编程 文本弹窗的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • TensorFlow中如何确定张量的形状实例

    TensorFlow中如何确定张量的形状实例

    这篇文章主要介绍了TensorFlow中如何确定张量的形状实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • 对python中arange()和linspace()的区别说明

    对python中arange()和linspace()的区别说明

    这篇文章主要介绍了对python中arange()和linspace()的区别说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python 中 AttributeError: ‘NoneType‘ object has no attribute ‘X‘ 错误问题解决方案

    Python 中 AttributeError: ‘NoneType‘ obje

    Python “AttributeError: ‘NoneType’ object has no attribute” 发生在我们尝试访问 None 值的属性时,例如 来自不返回任何内容的函数的赋值, 要解决该错误,请在访问属性之前更正分配,本文通过示例给大家说明错误是如何发生的,感兴趣的朋友一起看看吧
    2023-08-08
  • nginx黑名单和django限速,最简单的防恶意请求方法分享

    nginx黑名单和django限速,最简单的防恶意请求方法分享

    今天小编就为大家分享一篇nginx黑名单和django限速,最简单的防恶意请求方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-08-08
  • Python如何删除print()中的空格

    Python如何删除print()中的空格

    这篇文章主要介绍了Python如何删除print()中的空格问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • Python库学习Tkinter制作GUI个性签名设计软件

    Python库学习Tkinter制作GUI个性签名设计软件

    Tkinter 是 Python 中的标准 GUI 库,使用 Tkinter 可以快速地创建 GUI 应用程序。今天我们打算再用一个小案例,带大家加深对Tkinter的理解
    2021-09-09

最新评论