Python 别问 requests.request () 有多强大,问就是🐂byte

在路上 · 2020年10月29日 · 最后由 在路上 回复于 2020年10月30日 · 1671 次阅读

requests.request() 方法解析

(1)request 参数说明

  • method: 支持 GET, OPTIONS, HEAD, POST, PUT, PATCH, or DELETE.
  • url: str 类型
  • params: (可选) http 的 query。Dict, list of tuples or bytes to send.
params={'q': 'python', 'cat': '1001'}
  • data: (可选) Dictionary, list of tuples, bytes, or file-like
    • requests 默认使用 application/x-www-form-urlencoded 对 POST 数据编码
data={'form_email': 'abc@example.com', 'form_password': '123456'}
  • json: (可选) 如果要传递 JSON 数据,可以直接传入 json 参数:
params = {'key': 'value'}
requests.request(method="post", url="", json=params) # 内部自动序列化为JSON
  • headers: (可选) dict
  • cookies: (可选) dict
cs = {'token': '12345', 'status': 'working'}
requests.request(method="get", url="", cookies=cs)
  • files: (可选) 上传文件需要更复杂的编码格式,但是 requests 把它简化成 files 参数
    • 在读取文件时,注意务必使用'rb'即二进制模式读取,这样获取的 bytes 长度才是文件的长度
upload_files = {'file': open('report.xls', 'rb')}
requests.request(method="post", url="", files=upload_files)
  • auth: (可选) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  • timeout: (可选) 访问超时, float(wait for server to send data ) or tuple(connect timeout, read timeout)
  • allow_redirects: (可选) 重定向:Boolean. 默认为 true。 Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection.
  • proxies: (可选) 设置代理,可抓取所有 http 和 https 请求
proxies = {
  'http': 'http://10.100.57.47:8001',
  'https': 'http://10.100.57.47:8001',
}
requests.get('https://testerhome.com/', proxies=proxies)

  • verify: (可选) Boolean,控制是否验证,默认为 True。当 verify 为 True 时, 如果想解析 https 内容,需在 Cert 参数中添加证书路径
  • stream: (可选) 如果为``False'',则将立即下载响应内容。
  • cert: (可选) string 或 元组
    • string:为 ssl 客户端证书文件(.pem)的路径
    • 元组:(“证书”,“密钥”)配对

(2)response 参数说明

  • 返回状态码:r.status_code
  • Response Body:
    • str: r.text
    • Bytes: r.content
    • Dict: r.json()
  • Response Header(Dict): r.headers
  • 自动检测编码:r.encoding
  • 响应时间: int(r.elapsed.microseconds/1000) 毫秒
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 2 条回复 时间 点赞

确实牛逼,基本上能想到的需求都能满足

剪烛 回复

嗯嗯,最惊讶的是,还支持代理设置

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册