大湖之子 发表于 2018-8-8 09:26:04

python Requests 初级

  一、介绍
  Requests 是用Python语言编写,基于 urllib,但是它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 !
  二、用法
  1、使用 Requests 发送网络请求
import requests  
r = requests.get('https://github.com/timeline.json')
  
r = requests.post("http://httpbin.org/post")
  
r = requests.put("http://httpbin.org/put")
  
r = requests.delete("http://httpbin.org/delete")
  
r = requests.head("http://httpbin.org/get")
  
r = requests.options("http://httpbin.org/get")
  2、传递 URL 参数
    payload = {'key1': 'value1', 'key2': 'value2'}  
    r = requests.get("http://httpbin.org/get", params=payload)
  通过打印输出该 URL,你能看到 URL 已被正确编码:
    print(r.url)  
      http://httpbin.org/get?key2=value2&key1=value1
  3、响应内容
  r.text可以看到地址响应的内容
  Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。
  4、二进制响应内容
  你也能以字节的方式访问请求响应体
  r.content
  Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。
  例:以请求返回的二进制数据创建一张图片:
   from PIL import Image  
   from io import BytesIO
  
   i = Image.open(BytesIO(r.content))
  5、JSON 响应内容
  Requests 中也有一个内置的 JSON 解码器
   import requests  
   r = requests.get('https://github.com/timeline.json')
  r.json() 如果 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。
  6、定制请求头
   url = 'https://api.github.com/some/endpoint'  
   headers = {'user-agent': 'my-app/0.0.1'}
  
   r = requests.get(url, headers=headers)
  所有的 header 值必须是 string、bytestring 或者 unicode。
  7、更加复杂的 POST 请求
   payload = (('key1', 'value1'), ('key1', 'value2'))  
   r = requests.post('http://httpbin.org/post', data=payload)
  
   print(r.text)
  
(json直接传递)
  
   import json
  
   url = 'https://api.github.com/some/endpoint'
  
   payload = {'some': 'data'}
  
   r = requests.post(url, data=json.dumps(payload))
  8、响应状态码
  r.status_code(状态码)
  r.raise_for_status()   (抛出异常)
  9、响应头
  r.headers
  10、Cookie
url = 'http://example.com/some/cookie/setting/url'  
r = requests.get(url)
  
r.cookies['example_cookie_name']
  
'example_cookie_value'
  
发送你的cookies到服务器:(Cookie 的返回对象为 RequestsCookieJar)
  
r = 'http://httpbin.org/cookies'
  
cookies = dict(cookies_are='working')
  
r = requests.get(url, cookies=cookies)
  
r.text
  
'{"cookies": {"cookies_are": "working"}}'
  11、重定向与请求历史
  默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的 history 方法来追踪重定向。
  Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。
  例:Github 将所有的 HTTP 请求重定向到 HTTPS:
   r = requests.get('http://github.com')  
   r.url
  
   'https://github.com/'
  
   r.status_code
  
   200
  
   r.history
  
   [<Response >]
  可以通过 allow_redirects 参数禁用重定向处理:
   r = requests.get('http://github.com', allow_redirects=False)  
   r.status_code
  
   301
  
   r.history
  
   []
  12、超时
  你可以告诉 requests在经过以timeout参数设定的秒数时间之后停止等待响应。如果不使用,你的程序可能会永远失去响应:
  requests.get('http://github.com', timeout=0.001)
  注意:
  timeout仅对连接过程有效,与响应体的下载无关。timeout并不是整个下载响应的时间限制,而是如果服务器在timeout秒内没有应答,将会引发一个异常。
  13、错误与异常
  遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。
  如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
  若请求超时,则抛出一个 Timeout 异常。
  若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
页: [1]
查看完整版本: python Requests 初级