python常识系列18-->利用httpx模块发送请求

时间:2020-07-05 01:05:18   收藏:0   阅读:103

前言

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

一、httpx模块是什么?

二、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相同

三、小结:

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!