入门requents请求库使用

headers={}:user-agent:用户标识;referer:请求来源;content-type:请求参数类型。

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

1.安装 requests

第三方 需要安装的请求库,“pip install requests”。

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

pip install requests

 2.发送 GET 请求

get,params ;使用 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:

json:'Content-Type': 'application/json
data: 'Content-Type': 'application/x-www-form-urlencoded'

使用 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 参数。

你可能感兴趣的:(数据库,pip)