入门requents请求库使用

requests 是 Python 中一个非常流行的 HTTP 库,用于发送各种 HTTP 请求。以下是使用 requests 库的一些基本步骤:

1.安装 requests: 首先,确保已经安装了 requests 库。如果还没有安装,可以使用 pip 来安装:

pip install requests

 2.发送 GET 请求: 使用 get() 方法来发送一个 GET 请求:

url = "https://httpbin.org/get"
# 携带get请求参数
params = {
    "pn": 2,
    "size": 6
}
# 伪造请求头
headers = {
    # "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
}
res = requests.get(url, params=params)
for k, v in res.json().items():
    print(k, v)

 3.发送 POST 请求: 使用 post() 方法来发送一个 POST 请求,并携带数据:

使用json数据,如果需要发送 JSON 数据,可以使用 json 参数。设置请求头,使用 headers 参数来设置请求头。

import requests
# POST 用于提交用户数据

# 'Content-Type': 'application/x-www-form-urlencoded'
# 携带data数据  请求内容类型为表单数据
data = {
    "username": "fjg",
    "password": "123456"
}
res = requests.post("https://httpbin.org/post", data=data)

# 'Content-Type': 'application/json'
# 携带json数据  请求内容类型为json
json = {
    "username": "fjg",
    "password": "123456"
}
res = requests.post("https://httpbin.org/post")
print(res.json())

 4.发送其他类型的请求requests 库还支持 PUT、DELETE、HEAD 等 HTTP 方法。

5.使用会话: 如果你需要发送多个请求到同一个主机,可以使用 Session 对象来保持连接 。

6.处理异常: 使用 try-except 块来处理可能出现的异常。

7. 请求超时: 使用 timeout 参数来设置请求超时时间。

8.使用代理: 如果你需要通过代理发送请求,可以使用 proxies 参数。

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值