美文网首页
关于 python 网络请求 -- requests

关于 python 网络请求 -- requests

作者: Vissioon | 来源:发表于2017-05-31 15:20 被阅读255次

个人感觉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)
    

相关文章

  • 关于 python 网络请求 -- requests

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

  • Python自动化测试requests模块

    一、简介 requests库是 python 用来发送 http 请求。它是 Python 语言里网络请求库中最好...

  • 网络基础

    获取网络数据 python中使用第三方库requests来获取网络数据import requests 确定请求的地...

  • Python爬虫基础(一)

    本文简单介绍了requests的基本使用,python爬虫中requests模块绝对是是最好用的网络请求模块,可以...

  • 2018-08-10

    Python中requests请求报错requests.exceptions.ChunkedEncodingErr...

  • 爬虫基础:Requests模块

    Requests 是基于Python开发的HTTP网络请求库。 GET请求 POST 其他参数说明 无论是get还...

  • requests库核心API源码分析

    requests库是python爬虫使用频率最高的库,在网络请求中发挥着重要的作用,这边文章浅析requests的...

  • Python常用第三方库总结

    网络爬虫 网络请求 requests: Requests allows you to send HTTP/1.1 ...

  • python+requests

    【requests发送请求引言】 使用 Requests 发送网络请求非常简单。 一开始要导入 Requests ...

  • Python Requests库用法

    Requests库 Requests库是Python中提供HTTP请求的库,基于urllib。 GET请求 req...

网友评论

      本文标题:关于 python 网络请求 -- requests

      本文链接:https://www.haomeiwen.com/subject/vwpdfxtx.html