requests库——问题与解决办法(持续更新ing)

发布于 2022-05-11  1228 次阅读


requests库的请求中的参数

  1. 通用参数
  • proxies -- 设置代理(dict)
  • timeout -- 设置请求超时时间
  • headers -- 自定义设置请求头(dict)
  • url -- 设置请求目标地址
  • verify -- 是否认证SSL证书开关
  • cookies -- 指定请求使用cookie,并设置cookie值(dict)
  • cert -- 本地SSL证书路径
  1. requests.get
  • params -- 设置url中请求的参数(dict)
  • allow_redirects -- 是否跟随重定向
  1. requests.post
  • data -- post请求内容,发送包中格式为k1=v1&k2=v2……(dict)

  • json -- post请求内容,发送包中格式为JSON数据格式

  • files -- post请求内容,发送包中为文件,一般用在文件上传数据包中

requests库获取返回包内容

  • resp.text返回的是Unicode型的数据,取文本,可以通过resp.text。
  • resp.content返回的是bytes型的数据,取图片,文件,则可以通过resp.content。

requests库的requests.exceptions所有异常

  • requests.exceptions.HTTPError -- HTTP错误
  • requests.exceptions.ConnectionError -- 连接错误
  • requests.exceptions.ProxyError -- 代理错误
  • requests.exceptions.SSLError -- SSL错误
  • requests.exceptions.Timeout -- 请求超时错误,包含requests.exceptions.ConnectTimeout和requests.exceptions.ReadTimeout
  • requests.exceptions.ConnectTimeout -- 尝试连接到远程服务器时错误
  • requests.exceptions.ReadTimeout -- 服务器未在分配的时间内发送任何数据
  • requests.exceptions.URLRequired -- url格式错误
  • requests.exceptions.TooManyRedirects -- 过多的重定向
  • requests.exceptions.MissingSchema -- 网址架构(例如http或https)丢失
  • requests.exceptions.InvalidSchema -- 无效的架构
  • requests.exceptions.InvalidURL -- 无效的url
  • requests.exceptions.InvalidHeader -- 无效的请求头
  • requests.exceptions.InvalidProxyURL -- 无效的代理链接
  • requests.exceptions.ChunkedEncodingError -- 服务器声明了分块编码,但发送了无效的分块
  • requests.exceptions.ContentDecodingError -- 解码响应内容失败
  • requests.exceptions.StreamConsumedError -- 该响应的内容已被占用
  • requests.exceptions.RetryError -- 自定义重试逻辑失败
  • requests.exceptions.UnrewindableBodyError -- 尝试快退正文时,请求遇到错误

requests库的一些问题

  • 请求包data部分,requests库默认urlencode编码特殊字符例如\0b,暂时无有效应对方法
    • 已验证过的方法:修改requests库源码、格式化字符串、设置requests库请求编码格式等
    • 目前我使用的解决办法:更换使用urllib库及相关方法