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)
相关推荐
7***533426 分钟前
Rust错误处理模式
开发语言·后端·rust
上班日常摸鱼32 分钟前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
T***160737 分钟前
C++在游戏开发中的AI行为树
开发语言·c++
无心水1 小时前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶
2301_807583231 小时前
了解python,并编写第一个程序,常见的bug
linux·python
小白学大数据1 小时前
构建混合爬虫:何时使用Requests,何时切换至Selenium处理请求头?
爬虫·python·selenium·测试工具
2401_827560201 小时前
【Python脚本系列】PyAudio+librosa+dtw库录制、识别音频并实现点击(四)
python·语音识别
4***14901 小时前
Rust系统工具开发实践指南
开发语言·后端·rust
BBB努力学习程序设计1 小时前
Python自动化脚本:告别重复劳动
python·pycharm
BBB努力学习程序设计2 小时前
Python函数式编程:优雅的代码艺术
python·pycharm