内容概要

  • 如何构建GET 与 POST request 请求消息
  • 对 request 的header , query string, message body 定制化
  • http header参数 content-type 的设置
  • 分析request, response 消息数据
  • 通过POST请求上传文件
  • 请求与响应使用 json 格式

为什么推荐使用 requests 模块?

用 python 编写 http request 消息代码时,建议用requests库。因为requests比urllib内置库更为简捷,requests可以直接构造get,post请求并发送,而urllib.request只能先构造get,post请求消息内容,然后再发送。并且requests 模块提供了更友好的方法与属性来解析response消息内容。

1. 准备知识

1.1 HTTP request 与 Response 通讯机制

http协议是基于1种客户机(client) – 服务器(server) 的通信模式,它的下层是TCP协议。

  • 所有的请求request 都是由客户机发起的
  • 服务器对客户请求做出响应response
  • 每个request 都是独立于其它request消息,服务器不需要跟踪request消息的状态

1.2 Http Request 请求消息

客户端发送一个HTTP请求到服务器的请求消息由四个部分组成

  • 请求行(request line)
  • 请求头部(header)、
  • 空行(CLF)
  • 请求数据(payload,或body)

下图给出了请求报文的一般格式。


上图中,可以看到。Request 请求行第1个字节为请求方法, 有时也称动词(verb), 常用的主要有4种方法:GET, POST, PUT, DELETE

1.3 Http Response 响应消息

服务器的响应消息, 也是由4部分组成
状态行、消息报头、空行和响应正文

2. 安装 requests 模块

安装requests 模块非常简单,

pip install requests

3. GET 请求

3.1 request.get() 方法

用于准备并发送 http get 请求至指定url , 并返回response 对象

requests.get(url, params=None, **kwargs)

  • url: 拟获取页面的url链接
  • params: url中的额外参数,字典或字节流格式,可选
  • **kwargs: 可选参数,共有12个控制访问的参数

url格式:http://host_ip:port/path/add?key1=value1&key2=value2
传参数用字典类型:params={ key1: value1, key2: value2 }

response = requests.get('https://api.github.com/search/repositories',params={'q':'requests+language:python'},
)

可能遇到的问题:
如果参数中包含汉字 ,则会报编码错误,

可先进行编码, (将utf-8转为ascii码 )

urllib.parse.urlencode(dic)

解码:

urllib.parse.unquote(dic or str)

# 例1
keyword = input('请输入搜索关键字:')
param_list = urllib.parse.urlencode( { 'wd' : keyword } )
header = {'user-Agent':’haha‘}
url = 'http://www.baidu.com/s/'
response = request.get( url, params=param_list, headers = header )# 例2
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"}
request.get("http://www.baidu.com",headers=headers)
cookies = {"name":"haha"}
request.get("http://www.baidu.com",cookie=cookies)

3.2 Response 对象常用属性及方法

收到response后,需要分析 status_code,有必要可以对404, 500等出错响应进行特殊处理。

import requests
from requests.exceptions import HTTPErrorfor url in ['https://api.github.com', 'https://api.github.com/invalid']:try:response = requests.get(url)# If the response was successful, no Exception will be raisedresponse.raise_for_status()except HTTPError as http_err:print(f'HTTP error occurred: {http_err}')  # Python 3.6except Exception as err:print(f'Other error occurred: {err}')  # Python 3.6else:print('Success!')

当调用 .raise_for_status(), 对特定的status_code将产生1个 HTTPError 异常

Status_code

S.N. Code and Description
1 1xx: Informational It means the request was received and the process is continuing.
2 2xx: Success It means the action was successfully received, understood, and accepted.
3 3xx: Redirection It means further action must be taken in order to complete the request.
4 4xx: Client Error It means the request contains incorrect syntax or cannot be fulfilled.
5 5xx: Server Error It means the server failed to fulfill an apparently valid request.

常用方法

如果响应内 容是json格式,可以用Response.json()方法转换成 dict类型

异常 response 消息

如果发出request后,收到异常的response, 可以用下面的数据检查 :

>>> response = requests.post('https://httpbin.org/post', json={'key':'value'})
>>> response.request.headers['Content-Type']
'application/json'
>>> response.request.url
'https://httpbin.org/post'
>>> response.request.body
b'{"key": "value"}'

3.3 GET 方法的请求参数 Query String

get方法的请求参数是通过 params={ } 方式来传递的。

response = requests.get('https://api.github.com/search/repositories',params={'name': 'Jack','type':'display'},
)

4. POST 请求

4.1 POST 请求参数

与GET请求不同的是, POST 请求参数是放在 request body 里发送的, 向 request的 response对象传入的数据类型可以是 tuple, dict, json 等。

# 发送字典
post_dict = {'key1': 'value1', 'key2': 'value2'}
# 发送元组
post_tuple = (('key1', 'value1'), ('key1', 'value2'))
# 发送json
post_json = json.dumps({'some': 'data'})
r1 = requests.post("http://httpbin.org/post", data=post_dict)
r2 = requests.post("http://httpbin.org/post", data=post_tuple)
r3 = requests.post("http://httpbin.org/post", data=post_json)

输出: 以Json 格式发送 POST 请求

POST /echo/post/json HTTP/1.1
Authorization: Bearer mt0dgHmLJMVQhvjpNXDyA83vA_Pxh33Y
Accept: application/json
Content-Type: application/json
Content-Length: 85
Host: reqbin.com{"Id": 12345,"Customer": "John Smith","Quantity": 1,"Price": 10.00
}

收到 Response

HTTP/1.1 200 OK
Content-Length: 19
Content-Type: application/json{"success":"true"}

4.2 POST 消息设置 cookie, header

import requests
# 请求数据
url = 'http://api.shein.com/v2/member/login'cookie = "token=code_space;"
header = {"cookie": cookie,"Accept": "*/*","Accept-Encoding": "gzip, deflate, br","Accept-Language": "zh-CN,zh;q=0.9","Connection": "keep-alive","Content-Type": "application/json","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
}data = {'user_id': '123456','email': '123456@163.com'
}timeout = 0.5
resp = requests.post(url, headers=header, data=data, timeout=timeout)
print(resp.text)
print(type(resp.json()))

4.3 用 POST请求上传文件

客户端可通过POST请求,向服务器上传文件


#形式1
url = 'http://httpbin.org/post'
#定义文件对象
files = {"files":open('test.xls', 'rb')}
response = requests.post(url,files = files)
print(response.text)#形式2
url ='http://httpbin.org/post'
files = {'file': ('t.xls', open('t.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
r.text#形式3, 发送多个文件
url = 'http://httpbin.org/post'
files = {'file': ('t.csv', 'bb.csv')}
response = requests.post(url, files=files)
response.text

4. 请求与响应头部的 content-type 参数说明

Content-Type 参数告诉客户端,response实际返回数据的资源类型。这个参数在request 与 response中都可能包含,是 response 消息头部非常关键1个参数,也是开发者应该掌握的1个知识点。

语法格式示例 :

Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=something

content-type 格式为: key/value, 在http协议以及行业内,有很多通用的建议值,最常见的:

  • application/x-www-form-urlencoded, 这是提交表单默认的content-type设置, 对应form属性为 enctype.
  • multipart/form-data , 用于 form 上传文件
  • application/json 传json数据
  • text/csv 传送csv
  • text/html 传网页
  • text/plain text/xml 传文本
  • image/jpeg 传图片
  • video/mp4 传MP4视频

注:

  • 如果key 是 text类型,附件是中文,value 加编码类型:
    Content-Type: text/html; charset=UTF-8
  • 对于"application/x-www-form-urlencoded" 编码,如果两端都是用request编程,则不需要编解码,request 模块会自动完成。

下面是可能遇到的 content-type 的 key/value 列表:

Type Values
Application application/javascript
application/pdf
application/xhtml+xml
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
application/octet-stream : 二进制流数据(如常见的文件下载)
Audio audio/mpeg
audio/x-ms-wma
|audio audio/x-wav
Image image/gif
image/jpeg
image/png
image/tiff i
mage/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Multipart multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Text text/css
text/csv
text/html
text/plain
text/xml
Video video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
VND application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml

5. 用 json 做 payload

payload 就是通过http Post,get发送的数据,包括请求参数,文件,图片等, 发送方可以将用json类型来准备这些数据,接收方用json解开。

这在Header 里约定好。如下, 但注意,header 不能是json格式。

POST /echo/post/json HTTP/1.1
Host: reqbin.com
Accept: application/json
Content-Type: application/json
Content-Length: 52{"Id": 12345
}

response内容也可以用json来发送

{"success": "true","data": {"TotalOrders": 100}
}

6. 其它requests 方法

>>> requests.post('https://httpbin.org/post', data={'key':'value'})
>>> requests.put('https://httpbin.org/put', data={'key':'value'})
>>> requests.delete('https://httpbin.org/delete')
>>> requests.head('https://httpbin.org/get')
>>> requests.patch('https://httpbin.org/patch', data={'key':'value'})
>>> requests.options('https://httpbin.org/get')

使用 python requests 模块发送 http 请求及接收响应相关推荐

  1. Python中通过requests模块发送POST请求.

    博客核心内容: 1.Python中通过requests模块发送POST请求. 我们通常情况下提交数据一般有两种方式:Ajax和Form表单的方式 如果request.post里面没有值,我们就到req ...

  2. 爬虫之requests模块发送post请求

    爬虫之requests模块发送post请求 思考:哪些地方我们会用到POST请求? 登录注册( 在web工程师看来POST 比 GET 更安全,url地址中不会暴露用户的账号密码等信息) 需要传输大文 ...

  3. python requests是什么_如何基于Python + requests实现发送HTTP请求

    这篇文章主要介绍了如何基于Python + requests实现发送HTTP请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.在接口自动化测试 ...

  4. python使用 requests 模块发送http请求

    request 模块可以帮助我们发起http请求 步骤: 1.首先import 下 request 模块 2.然后看请求的方式,选择对应的请求方法 3.接受返回的报文信息 get 方法 (1)get请 ...

  5. pythonrequest函数_[Python]requests模块:HTTP请求时的回调函数

    前排提醒! 本文并非是"零起点"的.阅读下列文档之前,请保证你具有以下的知识: 了解requests和grequests模块,并能够使用其建立HTTP请求: 了解回调函数的含义. ...

  6. 爬虫之requests模块发送带参数的请求

    爬虫之requests模块发送带参数的请求 我们在使用百度搜索的时候经常发现url地址中会有一个 ?,那么该问号后边的就是请求参数,又叫做查询字符串 1.1 在url携带参数 直接对含有参数的url发 ...

  7. Python接口自动化-requests模块之post请求

    ------·今天距2021年262天·------ 这是ITester软件测试小栈第111次推文 在上一篇Python接口自动化测试系列文章:Python接口自动化-requests模块之get请求 ...

  8. 爬虫之requests模块发送带header的请求

    爬虫之requests模块发送带header的请求 我们先写一个获取百度首页的代码 import requestsurl = 'https://www.baidu.com'response = req ...

  9. mitmdump脚本中使用requests模块发送请求

    本文仅供学习交流使用,如侵立删! 环境 win10.Windows Server 2008 R2 python3.9 mitmdump4.0 mitmdump脚本中使用requests模块发送请求 m ...

最新文章

  1. linux下热插拔事件的产生是怎样通知到用户空间,kobject_uevent_env之uevent【转】...
  2. [转]MSDN - 在客户端脚本中为 UpdateProgress 控件编程
  3. 数据中心在颠覆性全球经济中的重要作用
  4. 【技术综述】“看透”神经网络
  5. python 计时器 timeit repeat 计算(语句)(函数)耗时 时间 运行时长
  6. struts2文件上传(2)
  7. java 多线程不安全_多线程并发为什么不安全
  8. javascript-变量的命名-数据类型-注释
  9. 获取网页上数据(图片、文字、视频)-b
  10. 【Vue起步-Windows】N01:环境安装
  11. azure模型训练_如何在Azure Machine Learning Studio上开发K-Means模型
  12. 从应届技术男到百度VP,这是低调到没百科的吴海锋首次受访
  13. 企业打开云HBase的正确方式,来自阿里云云数据库团队的解读
  14. VMware Workstation 6.0 正式版公布
  15. 【JAVA 数据结构】 JAVA实现动态数组
  16. Robotics Toolbox :(1)建立机器人模型
  17. linux777命令,linux权限777 命令是什么意思
  18. 关键字:c++builder(BCB) C# WebService EAccessViolation
  19. RabbitMQ报错ERROR: node with name rabbit already running on lhg1
  20. 企业微信号发消息给指定成员

热门文章

  1. 基于Python的收发包测试
  2. oracle怎么修改表的名称
  3. git灰度发布版本_灰度发布/蓝绿发布_部署到Kubernetes_选择部署方式_用户指南_CodePipeline - 阿里云...
  4. cpu time和clock time、real time、wall time都是什么?以及在不同语言中如何计算?
  5. 垃圾邮件冒充中国工商银行传播Sodinokibi勒索病毒
  6. NGINX配置PHP网站
  7. 全国领先,这个云顾问要火
  8. 激活anaconda环境
  9. 浏览器Cookie获取和设置
  10. GIT查看本地分支和远程分支