Urllib-R

Requests

  1. 介绍

    Requests 继承了urllib的所有特性。Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。

    requests 的底层实现其实就是 urllib3

    Requests的文档非常完备,中文文档也相当不错。Requests能完全满足当前网络的需求,支持Python 2.6—3.5,而且能在PyPy下完美运行。

    开源地址

    中文文档 API

  2. 安装

     pip install requests
    
  3. get请求

     import requests
    
     url='https://www.liepin.com/sh/zhaopin/pn1/?' \
         'd_pageSize=40&siTag=&d_headId=7523ef4c1e412df5e007f3cfd117447d&d_ckId=7523ef4c1e412df5e007f3cfd117447d&d_sfrom=' \
         'search_city&'
     qs={
         "key":"python",
         "d_curPage":0
     
     }
     
     headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
     # params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
     response = requests.get(url, params = qs, headers = headers)
     
     # 查看响应内容,response.text 返回的是Unicode格式的数据
     print(response.text)
     # 查看响应内容,response.content返回的字节流数据
     print(response.content)
     
     # 查看完整url地址
     print(response.url)
     
     # 查看响应头部字符编码
     print(response.encoding)
     
     # 查看响应码
     print(response.status_code)
     #查看以一个 Python 字典形式展示的服务器响应头
     
     print(response.headers)
    

    但是这个字典比较特殊:它是仅为 HTTP 头部而生的。根据 RFC 2616, HTTP 头部是大小写不敏感的。

    因此,我们可以使用任意大写形式来访问这些响应头字段:

     r.headers['Content-Type']
     r.headers.get('content-type')
    
  4. post 请求

    response = requests.post(url, data = data)

    如果是json文件可以直接显示

     print(response.json())
    

    如果 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

    需要注意的是,成功调用 r.json() 并意味着响应的成功。有的服务器会在失败的响应中包含一个 JSON 对象(比如 HTTP 500 的错误细节)。这种 JSON 会被解码返回。要检查请求是否成功,请使用 r.raise_for_status() 或者检查 r.status_code 是否和你的期望相同。

  5. 代理

    如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求

     import requests
    
     # 根据协议类型,选择不同的代理
     proxies = {
       "http": "http://12.34.56.79:9527",
       "https": "http://12.34.56.79:9527",
     }
     
     response = requests.get("http://www.baidu.com", proxies = proxies)
     print response.text
    
  6. 处理HTTPS请求 SSL证书验证

    要想检查某个主机的SSL证书,你可以使用 verify 参数(也可以不写)

     import requests
     response = requests.get("https://www.baidu.com/", verify=True)
     
     # 也可以省略不写
     # response = requests.get("https://www.baidu.com/")
     print r.text
    

猜你喜欢

转载自blog.csdn.net/ls_ange/article/details/83474354
R
R:
今日推荐