zoukankan      html  css  js  c++  java
  • python常识系列18-->利用httpx模块发送请求

    前言

       一个人至少拥有一个梦想,有一个理由去坚强。
    

    一、httpx模块是什么?

    • 一个用于http请求的模块,类似于requests、aiohttp;
    • 既能发送同步请求(是指在单进程单线程的代码中,发起一次请求后,在收到返回结果之前,不能发起下一次请求),又能发送异步请求(是指在单进程单线程的代码中,发起一次请求后,在等待网站返回结果的时间里,可以继续发送更多请求)。

    二、httpx模块基础使用

    2.1 httpx模块安装

    pip install httpx
    

    2.2 httpx模块基础使用

    import httpx
    
    res = httpx.get('http://www.hnxmxit.com/')
    print( res.status_code )
    print( res.headers )
    print( res.content.decode('utf8') )
    

    上述代码是通过httpx模块发送一个打开网站首页的情况,然后返回状态码、响应头信息的例子,读者应该发现和requests很像。

    2.2 模拟请求头

    import httpx
    
    get_param_data = {'wd':'湖南软测'}
    headinfos = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
                 'Accept-Encoding':'gzip,deflate,br',
                 'Accept-Language':'zh-CN,zh;q=0.9',
                 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
                 }
    response = httpx.get( url='https://www.baidu.com/s',params=get_param_data,headers=headinfos )
    print(response.content.decode('utf-8'))
    

    上述代码完成在百度中搜索 湖南软测 的例子,其实写法完全和requests相同

    三、小结:

    • requests 和 httpx都能模拟发送请求
    • 具一些大神测试后,httpx由于支持异步请求,所以发送大量的请求时,httpx的效率是优于requests的
  • 相关阅读:
    SpringBoot配置Druid数据源
    springboot自定义异常处理
    SpringBoot配置详解
    设计模式 | 模板方法模式(template method)
    设计模式 | 原型模式(prototype)
    设计模式 | 工厂方法模式(factory method)
    设计模式 | 代理模式(proxy)
    设计模式 | 装饰模式(decorator)
    设计模式 | 策略模式(strategy)
    设计模式 | 简单工厂模式(static factory method)
  • 原文地址:https://www.cnblogs.com/dream66/p/13237252.html
Copyright © 2011-2022 走看看