当前位置 博文首页 > requests在python中发送请求的实例讲解

    requests在python中发送请求的实例讲解

    作者:小妮浅浅 时间:2021-07-26 18:45

    当我们想给服务器发送一些请求时,可以选择requests库来实现。相较于其它库而言,这种库的使用还是非常适合新手使用的。本篇要讲的是requests.get请求方法,这里需要先对get请求时的一些参数进行学习,在掌握了基本的用法后,可以就下面的requests.get请求实例进一步的探究。

    1、get请求的部分参数

    (1) url(请求的url地址,必需 )

    import requests
    url="http://www.baidu.com"
    resp=requests.get(url)#向url对应的服务器发送相应的get请求,获得对应的相应 。

    (2)headers参数 请求头,可选

    import requests
    url=r"https://www.baidu.com/s"
    Headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
         }
    response=requests.get(url=url,headers=Headers)

    2、requests.get请求实例

    任何时候进行了类似 requests.get() 的调用,你都在做两件主要的事情。其一,你在构建一个 Request对象, 该对象将被发送到某个服务器请求或查询一些资源。其二,一旦 requests 得到一个从服务器返回的响应就会产生一个 Response 对象。该响应对象包含服务器返回的所有信息,也包含你原来创建的 Request 对象。如下是一个简单的请求,从 Wikipedia 的服务器得到一些非常重要的信息:

    >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

    如果想访问服务器返回给我们的响应头部信息,可以这样做:

    >>> r.headers
    
    {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
    
    'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
    
    'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
    
    'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
    
    'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
    
    must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
    
    'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
    
    MISS from cp1010.eqiad.wmnet:80'}

    然而,如果想得到发送到服务器的请求的头部,我们可以简单地访问该请求,然后是该请求的头部:

    >>> r.request.headers
    
    {'Accept-Encoding': 'identity, deflate, compress, gzip',
    
    'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}

    内容扩展:

    发送get请求

    # 导入requests模块
    import requests
    
    # 接口地址
    url = 'http://v.juhe.cn/historyWeather/citys'
    # 请求的参数数据
    da = {'key':'61e0c8a6d9614382afbaaf35dbd3ec6','province_id':'4'}
    # 发送请求
    r = requests.get(url,params=da)
    
    # 获取返回的json
    js = r.json()
    print(js)
    print(js['resultcode'])
    print(js['reason'])
    print(js['result'])
    print(js['error_code'])
    jsjbwy
    下一篇:没有了