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

目录
  • 一、requests
  • 二、requests安装方式
  • 三、说说常见的两种请求,get和post
    • 1、get请求
    • 2、post请求
  • 四、requests发送请求
  • 五、response
  • 补充: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请求内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python爬虫 基于requests模块发起ajax的get请求实现解析

    基于requests模块发起ajax的get请求 需求:爬取豆瓣电影分类排行榜 https://movie.douban.com/中的电影详情数据 用抓包工具捉取 使用ajax加载页面的请求 鼠标往下下滚轮拖动页面,会加载更多的电影信息,这个局部刷新是当前页面发起的ajax请求, 用抓包工具捉取页面刷新的ajax的get请求,捉取滚轮在最底部时候发起的请求 这个get请求是本次发起的请求的url ajax的get请求携带参数 获取响应内容不再是页面数据,是json字符串,是通过异步请求获取的电影

  • Python requests发送post请求的一些疑点

    前言 在Python爬虫中,使用requests发送请求,访问指定网站,是常见的做法.一般是发送GET请求或者POST请求,对于GET请求没有什么好说的,而发送POST请求,有很多朋友不是很清楚,主要是因为容易混淆 POST提交的方式 .今天在微信交流群里,就有朋友遇到了这种问题,特地讲解一下. 在HTTP协议中,post提交的数据必须放在消息主体中,但是协议中并没有规定必须使用什么编码方式,从而导致了 提交方式 的不同.服务端根据请求头中的 Content-Type 字段来获知请求中的消息主体

  • python爬虫使用requests发送post请求示例详解

    简介 HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式.服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析.具体的编码方式包括: application/x-www-form-urlencoded 最常见post提交数据的方式,以form表单形式提交数据. application/json 以json串提交数据. multipart/form-data 一般使用来上传文件. 一. 以f

  • python爬虫 基于requests模块的get请求实现详解

    需求:爬取搜狗首页的页面数据 import requests # 1.指定url url = 'https://www.sogou.com/' # 2.发起get请求:get方法会返回请求成功的响应对象 response = requests.get(url=url) # 3.获取响应中的数据:text属性作用是可以获取响应对象中字符串形式的页面数据 page_data = response.text # 4.持久化数据 with open("sougou.html","w&

  • python 使用 requests 模块发送http请求 的方法

    Requests具有完备的中英文文档, 能完全满足当前网络的需求, 它使用了urllib3, 拥有其所有的特性! 最近在学python自动化,怎样用python发起一个http请求呢? 通过了解 request 模块可以帮助我们发起http请求 步骤: 1.首先import 下 request 模块 2.然后看请求的方式,选择对应的请求方法 3.接受返回的报文信息 例子:get 方法 import requests url ="https://www.baidu.com" res =

  • python requests 库请求带有文件参数的接口实例

    有些接口参数是一个文件格式,比如fiddler 抓包参数如下显示 这个接口的 form-data fiddler 显示的和不带文件参数的接口有明显区别,显示的不是简单的键值对,所以我们也不能只通过 data给接口传参,需要再value为<file>的参数通过 files传参 data = { "CSRFName": "CSRFName", "CSRFToken": "CSRFToken", "import

  • Python使用requests发送POST请求实例代码

    本文研究的主要是Python使用requests发送POST请求的相关内容,具体介绍如下. 一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样: 请求行 请求报头 消息主体 HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式.服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析.具体的编码方式包括: application/x-www-form-urlencode

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

    目录 一.requests 二.requests安装方式 三.说说常见的两种请求,get和post 1.get请求 2.post请求 四.requests发送请求 五.response 补充:requests中遇到问题 总结 一.requests request的说法网上有很多,简单来说就是就是python里的很强大的类库,可以帮助你发很多的网络请求,比如get,post,put,delete等等,这里最常见的应该就是get和post 二.requests安装方式 $ pip install r

  • Python中使用Lambda函数的5种用法

    引言 Lambda 函数(也称为匿名函数)是函数式编程中的核心概念之一. 支持多编程范例的 Python 也提供了一种简单的方法来定义 lambda 函数. 用 Python 编写 lambda 函数的模板是: lambda arguments : expression 它包括三个部分: · Lambda 关键字 · 函数将接收的参数 · 结果为函数返回值的表达式 由于它的简单性,lambda 函数可以使我们的 Python 代码在某些使用场景中更加优雅.这篇文章将演示在 Python 中 la

  • python中requests库安装与使用详解

    目录 前言 1.Requests介绍 2.requests库的安装 3.requests库常用的方法 4.response对象的常用属性 5.使用requests发送get请求 5.1  不带参数的get请求 5.2 带参数的get请求 5.2.1 查询参数params 5.2.2 SSL证书认证参数 verify 5.2.3 设置超时时间 timeout 5.2.4 代理IP参数 proxies 5.3 获取JSON数据 5.4 获取二进制数据 6.使用requests发送post请求 7.使

  • python中requests模拟登录的三种方式(携带cookie/session进行请求网站)

    一,cookie和session的区别 cookie在客户的浏览器上,session存在服务器上 cookie是不安全的,且有失效时间 session是在cookie的基础上,服务端设置session时会向浏览器发送设置一个设置cookie的请求,这个cookie包括session的id当访问服务端时带上这个session_id就可以获取到用户保存在服务端对应的session 二,爬虫处理cookie和session 带上cookie和session的好处: 能够请求到登录后的界面 带上cook

  • requests在python中发送请求的实例讲解

    当我们想给服务器发送一些请求时,可以选择requests库来实现.相较于其它库而言,这种库的使用还是非常适合新手使用的.本篇要讲的是requests.get请求方法,这里需要先对get请求时的一些参数进行学习,在掌握了基本的用法后,可以就下面的requests.get请求实例进一步的探究. 1.get请求的部分参数 (1) url(请求的url地址,必需 ) import requests url="http://www.baidu.com" resp=requests.get(url

  • python中Requests发送json格式的post请求方法

    目录 前言 1.普通string类型 2.string内是字典的 3.元组(嵌套列表或者) 4.字典 5.json 6.传入非嵌套元组或列表 7.以post(url,json=data)请求 前言 问题: 做requests请求时遇到如下报错: {“code”:“500”,“message”:"JSON parse error: Cannot construct instance of com.bang.erpapplication.domain.User (although at least

  • python中requests库+xpath+lxml简单使用

    python的requests 它是python的一个第三方库,处理URL比urllib这个库要方便的多,并且功能也很丰富. [可以先看4,5表格形式的说明,再看前面的] 安装 直接用pip安装,anconda是自带这个库的. pip install requests 简单使用 requests的文档 1.简单访问一个url: import requests url='http://www.baidu.com' res = requests.get(url) res.text res.statu

  • Python中requests库的基本概念与具体使用方法

    目录 一. 基本概念 1. 简介 2. 获取 3. http 协议 3.1 URL 3.2 常用 http 请求方法 二. 使用方法 1. 基本语法 2. 具体使用方法 2.1 get 2.2 post 2.3 response 2.4 head 2.5 put 总结 一. 基本概念 1. 简介 requests 模块是 python 基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测

  • python中requests使用代理proxies方法介绍

    学习网络爬虫难免遇到使用代理的情况,下面介绍一下如何使用requests设置代理: 如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求: import requests proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://examp

  • python中requests爬去网页内容出现乱码问题解决方法介绍

    最近在学习python爬虫,使用requests的时候遇到了不少的问题,比如说在requests中如何使用cookies进行登录验证,这可以查看这篇文章.这篇博客要解决的问题是如何避免在使用requests的时候出现乱码. import requests res=requests.get("https://www.baidu.com") print res.content 以上就是使用requests进行简单的网页请求数据的方式.但是很容易出现乱码的问题. 我们可以通过在网页上右击查看

随机推荐