关于 python 网络请求 -- requests

个人感觉requests比urllib&urllib2好用 (不过requests基于urllib)

  • 安装

    pip install requests
    
  • get请求

    r = requests.get('http://www.baidu.com')
    
  • post请求

    data = {
        'hello': 'hello'
    }
    r = requests.post('http://www.baidu.com', data)
    
  • headers

    headers = {  # 请求headers
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
                              '(KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
                'Connection': 'keep-alive',
            }
    r = requests.get('http://www.baidu.com', headers=headers)
    
  • 代理

    proxies = {
        'http':'http://192.168.1.171'
    }
    r = requests.get('http://www.baidu.com', proxies=proxies)
    
  • session共享

    s = requests.session
    s.get()
    s.post()  #后面的请求会带上前面的cookies
    
  • response

    r = requests.get('http://www.baidu.com')
    r.text                  # 字符串方式的响应体,会自动根据响应头部的字符编码进行解码
    r.status_code           # 响应状态码
    r.raw                   # 返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
    r.content               # 字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
    r.headers               # 以字典对象存储服务器响应头
    r.json()                # requests中内置的JSON解码器
    r.raise_for_status()    # 失败请求(非200响应)抛出异常
    
  • 超时

    r = requests.get('http://www.baidu.com', timeout=3) #秒为单位
    
  • 文件

    url = 'http://localhost/upload'
    files = {
        'file': open('/home/john/hello.txt', 'rb')
    }
    r = requests.post(url, files=files)
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容