python requests http请求

时间:2022-01-13 22:23:50
  • 导入模块
import requests
import json header = {'Content-Type': 'application/json'}
data = {"": ""}
data = json.dumps(data)
endpoint = "http://www.baidu.com/"
  • 常用操作
request = requests.get(endpoint + "get")
request = requests.head(endpoint + "get")
request = requests.delete(endpoint + "delete")
request = requests.options(endpoint + "options")
request = requests.put(endpoint + "put",data=data)
request = requests.post(endpoint + "post", data=data, headers=header)
  • 不验证https证书
request = requests.get(endpoint,verify=False)
  • 请求超时
request = requests.get(endpoint,timeout=5)
  • 测试url是否正常
try:
data = str(requests.head('http://www.baidu.com', timeout=5))
except:
print("有问题")
else:
print("没问题")
  • 打印返回
#打印返回的http状态码
print(request.status_code)
#打印请求的地址
print(request.url)
#json格式打印返回的数据
print(request.json())
#文本格式打印返回的数据
print(request.text)