http请求之requests

Requests

get请求

Requests模块,继承了urllib2的所有特性,支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传等,本质就是封装了urllib3

常用API

  • response.status_code(返回状态码)
  • response.text(返回文本)
  • response.content(返回二进制流)
  • response.json()(返回json文件)
import requests
# response = requests.get("https://api.xdclass.net/pub/api/v1/web/all_category")
# print(response.text)
data = {"video_id":53}
response = requests.get("https://api.xdclass.net/pub/api/v1/web/video_detail?",data)
#http状态码 response.status_code
print(response.status_code)
#Requests 会基于 HTTP 响应的文本编码自动解码响应内容,大多数 Unicode 字符集都能正常解码。
print(response.text)
#返回的是服务器响应数据的原始二进制字节流,一般用来保存图片等二进制文件
print(response.content)
print(response.json())

Post请求

post提交方式有两个传参方式,针对不同的content-type, 务必要指定接口是哪个类型,表单提交还是json提交

**def post(url, data=None, json=None, ****kwargs)

# Content-Type: application/x-www-form-urlencoded
# requests.post("url", data=data)

# Content-Type: application/json
# requests.post("url", json=data)
# -*- coding:UTF-8 -*-
import requests

data = {"phone":***,"pwd":"***"}
response = requests.post("https://api.xdclass.net/pub/api/v1/web/web_login",data=data)
print(response.status_code)
print(response.text)
print(response.json())

运行报错:requests.exceptions.SSLError: HTTPSConnectionPool(host=‘XXX’, port=443)

解决:

  1. #在请求中加入verify=False,关闭认证-,解决requests.exceptions.SSLError
    response = requests.post("https://api.xdclass.net/pub/api/v1/web/web_login",data=data,verify=False)
    
  2. #导入urllib3,解决InsecureRequestWarning
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    

Headers

请求增加Header信息

原文地址:https://www.cnblogs.com/wennyjane/p/14249291.html