Python Requests 库的基本使用
Requests 库的基本用法,内含对 HTTP 请求方法的介绍,request 和 response 类的介绍,Session 类的使用,附加参数的选择等等。
创建请求 Creating requests
安装与引入
pip3 install requests
import requests
十分简单,不再赘述.
选择请求方法
HTTP 定义了一组请求方法, 以表明要对给定资源执行的操作。指示针对给定资源要执行的期望动作。
- GET
GET 方法请求一个指定资源的表示形式. 使用 GET 的请求应该只被用于获取数据.- HEAD
HEAD 方法请求一个与 GET 请求的响应相同的响应,但没有响应体.- POST
POST 方法用于将实体提交到指定的资源,通常导致在服务器上的状态变化或副作用.- PUT
PUT 方法用请求有效载荷替换目标资源的所有当前表示。- DELETE
DELETE 方法删除指定的资源。- CONNECT
CONNECT 方法建立一个到由目标资源标识的服务器的隧道。- OPTIONS
OPTIONS 方法用于描述目标资源的通信选项。- TRACE
TRACE 方法沿着到目标资源的路径执行一个消息环回测试。- PATCH
PATCH 方法用于对资源应用部分修改。我们常说的 CRUD (Create, Read/Retrieve, Update, Delete) 可以说成
增删查改
,即对应前四种方法。参考资料:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods
我们就可以采用对应的 requests
模块所提供的方法来创建请求.
requests.get(url, params=None, **kwargs)
requests.head(url, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)[source]
requests.delete(url, **kwargs)
当然,我们也可以使用简单的request
方法来构建请求。
requests.request(method, url, **kwargs)
# Where method should be one of GET, OPTIONS, HEAD, POST, PUT, PATCH, or DELETE.
添加可选参数
这里仅列出部分常用参数.
- params: Dict
Mainly used for GET method. 帮助构建 Query 字符串。
- data : str | json : Dict
Mainly used for POST/PUT method. 作为 Request Body.
URL = PluginManager.CONFIGURATION['destinations']['QQ']['http-adapter-address']
res = requests.post(URL+'/sendFriendMessage', headers={'Content-Type': 'application/json'}, json=({"target": destination.content, "messageChain": [{"type": "Plain", "text": "hello world"}]}))
// Equals to data="JSON STRING"
print(res.json())
- headers : Dict
# Example
response = requests.get(URL, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'})
- cookies: Dict
# Attached: get cookies in Dict from documen.cookie
def getCookies():
f = open("cookies")
data = f.read().replace(" ", "").replace("\"", "").replace("\n", "").split(";")
result = {}
for entry in data:
print(entry)
entryGroup = entry.split("=")
result[entryGroup[0]] = entryGroup[1]
return result
# Maybe the code could be more pythonic...??
- timeout: float (seconds)
(Optional) 使用 Session
如果只需要对单个链接进行数据获取,那么我们上述的方法执行一次就够了.
但是某些网站可能需要前后访问的 Session 是一致的,这样才能够实现,先 Login 后 Verify 等等操作…
这时就需要我们的 Session 类了.
s = requests.Session()
s.headers = {} # Configurate headers
s.get('https://httpbin.org/get')
# Other Operations with s...
s.close()
提取响应 Parsing responses
上述方法的返回值为 Response
类的对象。
Response
类的对象具有以下常用属性。
- ok
Returns true if return code is less than 400.
- text
Content of the response, in unicode.
- json(**kwargs)
Returns the json-encoded content of a response if any.