python Requests

Requests概述

官方文档:http://cn.python-requests.org/zh_CN/latest/,Requests是python的HTTP的库,我们可以安全的使用

Requests安装

复制代码
pip install Requests -i https://pypi.tuna.tsinghua.edu.cn/simple

Requests的使用

Respose的属性

属性 说明
url 响应的URL
text 响应的内容 (unicode码)
json() 如果响应的结果是一个json对象,可以调用该方法,否则会报错
content 返回响应的内容(字节的形式)
status_code 响应代码,其中200表示响应成功,404表示Not Found等等

Requests GET请求

requests.get()函数将会返回服务器的响应

python 复制代码
import requests

headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"}
params = {"spm":"1001.2014.3001.5502"}
url = "https://blog.csdn.net/qq_42103091/article/details/123287865"

response = requests.get(url=url, params=params, headers=headers)
# 响应的URL
print(response.url)
# https://blog.csdn.net/qq_42103091/article/details/123287865?spm=1001.2014.3001.5502
# 状态码
print(response.status_code)
# 200

Requests POST请求

倘若需要向服务器上传数据,一般采用POST请求。常见的应用场景为提交HTML表单。

POST请求中的Content-Type用来指示请求正文的数据类型,而Content-Length则指示了请求中的数据长度

python 复制代码
requests.post(url, data, json, headers, proxies, timeout, vertify)
# 参数说明
"""
url: 请求的URL
data: 发送给指定URL的字典、元组列表、字节或文件对象
json: 发送给指定URL的JSON对象
headers、proxies、timeout、vertify: 与get()方法同
"""

发送请求

python 复制代码
import requests
import json

url = "https://httpbin.org/post"

data = {
    "comments": "ceshi", 
    "custemail": "ceshi.com", 
    "custname": "ceshi", 
    "custtel": "ceshi", 
    "delivery": "17:30", 
    "size": "large", 
    "topping": "onion"
}

response = requests.post(url=url, data=data)
print(response.status_code)

# 200
with open("temp.json", "w", encoding="utf-8") as fp:
    json.dump(response.json(), fp, ensure_ascii=False)
相关推荐
AI爱好者2 分钟前
WordPress保卫战:用Python分析日志并封禁恶意爬虫
python
ouliten8 分钟前
C++笔记:std::stringbuf
开发语言·c++·笔记
Rhys..9 分钟前
Jenkinsfile保存在项目根目录下的好处
java·开发语言
lly20240611 分钟前
SQL LCASE() 函数详解
开发语言
0***K89221 分钟前
PHP框架比较
开发语言·php
哟哟耶耶22 分钟前
ts-属性修饰符,接口(约束数据结构),抽象类(约束与复用逻辑)
开发语言·前端·javascript
nvd1132 分钟前
Gidgethub 使用指南
开发语言·python
___波子 Pro Max.39 分钟前
Python模块导入详解与最佳实践
python
讨厌下雨的天空1 小时前
线程同步与互斥
java·开发语言
娶不到胡一菲的汪大东1 小时前
C# 泛型 委托 接口
开发语言·windows·c#