• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python-包之-httpx-请求操作教程

python 搞代码 3年前 (2022-04-09) 30次浏览 已收录 0个评论

一、装置
httpx是Python新一代的网络申请库
httpx与 requests 库的根本应用办法简直是截然不同的
基于Python3的功能齐全的http申请模块
既能发送同步申请,也能发送异步申请
反对HTTP/1.1和HTTP/2
反对间接向WSGI应用程序或者ASGI应用程序发送申请

pip install httpx

二、申请类型

import httpx
httpx.get('https://www.baidu.com')
httpx.post('https://www.baidu.com')
httpx.put('https://www.baidu.com')
httpx.delete('https://www.baidu.com')
httpx.head('https://www.baidu.com')
httpx.options('https://www.baidu.com')

三、带参数申请

import httpx

data = {
    'name': 'autofelix',
    'age': 25
}

response = httpx.get('https://www.baidu.com', params=data)
print(response.url)
print(response.text)

四、自定义 headers

import httpx

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
response =httpx.get('https://www.baidu.com', headers=headers)
print(response.text)

五、申请的属性

import httpx

response = httpx.get('https://www.baidu.com')

# 响应状态码
response.status_code
# 响应头
response.headers
# 响应cookie
response.cookies
# 申请url
response.url
# 历史记录
response.history

六、应用client发送申请

import httpx

with httpx.Client() as client:
    response = client.get('https://www.baidu.com')
    print(response.text)

七、HTTP代理

import httpx

proxies= {
    'http': 'http://127.0.0.1:9999',
    'https': 'http://127.0.0.1:8888'
}

with httpx.Client(proxies=proxies) as client:
    response = client.get('https://www.baidu.com')
    print(response)

八、超时解决

import httpx

# 一般申请超时解决
httpx.get('https://www.baidu.com', timeout=10.0)

# 一般申请敞开超时解决
httpx.get('https://www.baidu.com', timeout=None)

# client实例超时解决
with httpx.Client() as client:
    client.get('https://www.baidu.com', timeout=None)
    
# client实例敞开超时解决
with httpx.Client() as client:
    client.get('https://www.baidu.com', timeout=10.0)

九、SSL验证

import httpx

# 自带ca证书
response = httpx.get('https://www.baidu.com', verify="path/cert/client.pem")

# 齐全禁用SSL验证
response = httpx.get('https://www.baidu.com', verify=False)

十、异步操作
应用async/await语句来进行异步操作
应用异步client比应用多线程发送申请更加高效,更能体现显著的性能劣势

import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client: 
        response = await client.get('https://www.baidu.com')
        print(response)

if __name__ == '__main__':
    asyncio.run(main())

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注Python技术大本营,获取更多技能与教程。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python-包之-httpx-请求操作教程

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址