官方文档真是好用的一匹

官方文档:https://2.python-requests.org//zh_CN/latest/index.html

参考blog:https://www.cnblogs.com/humiao-0626/category/1465538.html

1. 快速上手

# -*- coding:utf-8 -*-
"""
requests模块
https://2.python-requests.org//zh_CN/latest/index.html
""" import requests#

1 发送请求

r = requests.get("https://www.cnblogs.com/")  #  r: Response 对象
print(r) # r = requests.post("http://httpbin.org/post",data={'key':'value'})
# r = requests.put("http://httpbin.org/put",data={'key':'value'})
# r = requests.delete("http://httpbin.org/delete")
# r = requests.head("http://httpbin.org/get")
# r = requests.options("http://httpbin.org/get")

2 传递url参数

# payload = {"key1":"value1","key2":"value2"}
payload = {"key1":"value1","key2":["value2","value3"]} r = requests.get("http://httpbin.org/get",params=payload) #print(r.url) # http://httpbin.org/get?key1=value1&key2=value2
print(r.url) # http://httpbin.org/get?key1=value1&key2=value2&key2=value3

3 响应内容

r = requests.get("https://api.github.com/events")
print(r.text) # response 编码类型
print(r.encoding) # utf-8 print(r.content) # b'[{"id":"10124980852","type":"PushEvent","actor":{"id":387
# 比如 HTTP 和 XML 自身可以指定编码。
# 这样的话,你应该使用 r.content 来找到编码,
# 然后设置 r.encoding 为相应的编码。这
# 样就能使用正确的编码解析 r.text 了。

4 二进制响应内容

print(r.content)  #  # b'[{"id":"10124980852","type":"PushEvent","actor":{"id":387
# Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。 # 以请求返回的二进制数据创建一张图片
'''
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
'''

5 JSON响应内容

r = requests.get('https://api.github.com/events')
r.json() # b'[{"id":"10125000497","type":"PushEvent","actor":{"id":28391787,"login":"m1ha5","display_login":"m1"}}] # 响应内容是 401 (Unauthorized),尝试访问 r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。
# 要检查请求是否成功,请使用 r.raise_for_status() 或者检查 r.status_code 是否和你的期望相同
# print(r.raise_for_status())
print(r.status_code)

6 原始响应内容

    # 想获取来自服务器的原始套接字响应
# 确保在初始请求中设置了 stream=True
r= requests.get('https://api.github.com/events', stream=True)
print(r.raw) # <urllib3.response.HTTPResponse object at 0x000001D3FD5525C0> # print(r.raw.read(10)) # b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
# 下面的模式将文本流保存到文件
with open('test.txt','wb') as fd:
for chunk in r.iter_content(chunk_size=10):
fd.write(chunk)

7 定制请求头

url = "https://api.github.com/some/endpoint"
headers = {'user-agent':'my-app/0.0.1'}
r = requests.get(url,headers=headers)
# 定制 header 的优先级低于某些特定的信息源
# 注意: 所有的 header 值必须是 string、bytestring 或者 unicode。

8 更加复杂的 POST 请求

url = 'http://httpbin.org/post'
# payload = {'key1':'vaule1','key2':'value2'} # 为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:
payload = (('key1','value1'),('key1','value1')) r = requests.post(url=url,data=payload)
print(r.text) # 返回response的内容 # 发送的数据并非编码为表单形式 你传递一个 string
# 例如,Github API v3 接受编码为 JSON 的 POST/PATCH 数据:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some':'data'} # 自行对dict进行编码
# r = requests.post(url=url,data=json.dumps(payload)) # 用 json 参数直接传递
r = requests.post(url=url,json=payload) print(r.text)

9 POST一个多部分编码(Multipart-Encoded)的文件

官方文档

10 响应状态码

url = "http://httpbin.org/get"
r = requests.get(url=url)
print(r.status_code)
print(r.status_code == requests.codes.ok) # True # Requests还附带了一个内置的状态码查询对象 # if 发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),
# 我们可以通过 Response.raise_for_status() 来抛出异常
url="http://httpbin.org/status/404"
bad_r = requests.get(url=url)
print(bad_r.status_code)
# print(bad_r.raise_for_status())

11 响应头

print(r.headers) # 字典

'''
{
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
'Content-Encoding': 'gzip',
'Content-Type': 'application/json',
'Date': 'Thu, 01 Aug 2019 02:59:19 GMT',
'Referrer-Policy': 'no-referrer-when-downgrade',
'Server': 'nginx',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Content-Length': '184',
'Connection': 'keep-alive'
}
''' print(r.headers['Content-Type'])
print(r.headers.get('Content-Type')) # 服务器可以多次接受同一 header,每次都使用不同的值

12 cookie

# 某个响应中包含一些 cookie,你可以快速访问它们
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url=url)
print(r.cookies) # <RequestsCookieJar[]>
# print(r.cookies['example_cookie_name']) # 发送你的cookies到服务器,可以使用 cookies 参数
url= 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url=url,cookies=cookies)
print(r.text) # '{"cookies": {"cookies_are": "working"}}' # Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似
# 适合跨域名跨路径使用。你还可以把 Cookie Jar 传到 Requests 中 jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie','yum',domain='httpbin.org',path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url=url,cookies=jar)
print(r.text) # '{"cookies": {"tasty_cookie": "yum"}}' #

13 重定向与请求历史

官方文档

14 超时错误

# requests 在经过以 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)
''' '''
timeout 仅对连接过程有效,与响应体的下载无关
timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常
是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时
'''

15 错误与异常

'''
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
若请求超时,则抛出一个 Timeout 异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。
'''

1 request模块的更多相关文章

  1. dojo/request模块整体架构解析

    总体说明 做前端当然少不了ajax的使用,使用dojo的童鞋都知道dojo是基于模块化管理的前端框架,其中对ajax的处理位于dojo/request模块.一般情况下我们使用ajax请求只需要引入do ...

  2. node.js的request模块

    request模块让http请求变的更加简单.最简单的一个示例: 1: var request = require('request'); 2:  3: request('http://www.goo ...

  3. python接口自动化测试(一)-request模块

    urllib.request模块是python3针对处理url的. 1. 首先导入: from urllib import request 2. 构造url,构造url的headers信息和传参[re ...

  4. request 模块详细介绍

    request 模块详细介绍 request Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装 ...

  5. 第5月第10天 node.js的request模块

    1.node.js的request模块 http://www.cnblogs.com/meteoric_cry/archive/2012/08/18/2645530.html

  6. 【nodejs】理想论坛帖子下载爬虫1.07 使用request模块后稳定多了

    在1.06版本时,访问网页采用的时http.request,但调用次数多以后就问题来了. 寻找别的方案时看到了https://cnodejs.org/topic/53142ef833dbcb076d0 ...

  7. python flask的request模块以及在flask编程中遇到的坑

    一.首先来讲讲遇到的坑: 1.linux下package的打包引用: """ 路径结构如下: ./project ./bin ./api ""&quo ...

  8. 爬虫之urllib包以及request模块和parse模块

    urllib简介 简介 Python3中将python2.7的urllib和urllib2两个包合并成了一个urllib库 Python3中,urllib库包含有四个模块: urllib.reques ...

  9. python3中urllib库的request模块详解

    刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...

  10. nodejs的request模块

    request模块让http请求变的更加简单.(作为客户端,去请求.抓取另一个网站的信息) request的GitHub主页: https://github.com/request/request 最 ...

随机推荐

  1. Design Circular Queue

    Design your implementation of the circular queue. The circular queue is a linear data structure in w ...

  2. Kick Start 2019 Round H. Elevanagram

    设共有 $N = \sum_{i=1}^{9} A_i$ 个数字.先把 $N$ 个数字任意分成两组 $A$ 和 $B$,$A$ 中有 $N_A = \floor{N/2}$ 个数字,$B$ 中有 $N ...

  3. 20190507-学习dubbo有感于梁飞

    “作为一名程序员,BAT肯定是大多数人都想进的,仿佛是一种情愫,就像学生时代的我们对清华北大的向往感觉一样.Dubbo团队中,其中主要负责人就是梁飞了,梁飞的经历还是蛮励志的.梁飞,花名虚极, 200 ...

  4. Linux系列(5):入门之文件类型与扩展名

    通过本章你会了解到: 文件类型有哪些? 文件扩展名的意义是什么? 1.文件类型 任何设备在Linux系统中都是文件,不仅如此,连数据沟通的接口也有专属的文件在负责,所以Linux的文件种类真的很多,除 ...

  5. PAT A1046 Shortest Distance (20 分)

    题目提交一直出现段错误,经过在网上搜索得知是数组溢出,故将数组设置的大一点 AC代码 #include <cstdio> #include <algorithm> #defin ...

  6. win10的修改hosts文件

    1.找到hosts文件 2.右键hosts文件 -> 属性  -> 安全 ->  编辑 3.依次选中用户组用户组,完全控制打钩,点击应用,点击确定,完成. 一般情况下这样就能修改了 ...

  7. Codeforces 1244F. Chips

    传送门 显然可以注意到连续的两个相同颜色的位置颜色是不会改变的,并且它还会把自己的颜色每秒往外扩展一个位置 同时对于 $BWBWBW...$ 这样的序列,它每个位置的颜色每一秒变化一次 然后可以发现, ...

  8. Java EE javax.servlet中的ServletContext接口

    ServletContext接口 public interface ServletContext (https://docs.oracle.com/javaee/7/api/javax/servlet ...

  9. EasyUI_前台js_分页

    1.html: <table id="DataTb" title="客户信息" class="easyui-datagrid" sty ...

  10. 对接外网post,get接口封装类库

    public class HttpHelper { public static string GetAsync(string url)  { HttpWebRequest request = WebR ...