千家信息网

python中Requests库有什么用

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,这篇文章主要介绍了python中Requests库有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。1.Requests简介请求是
千家信息网最后更新 2025年12月02日python中Requests库有什么用

这篇文章主要介绍了python中Requests库有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

1.Requests简介

请求是唯一适用于Python的Non-GMO HTTP库,可供人类安全使用。

Python爬虫中绕过不开的就是requests库。而Requests引用urllib在使用方面上引起开发者感到更加人性化,更加简洁,更加舒适。以下摘自Requests官方文档中的功能特性:

  1. 保持活力和连接池

  2. 国际化域名和URL

  3. 带永久Cookie的会话

  4. 浏览器式的SSL认证

  5. 自动内容解码

  6. 基本/摘要式的身份认证

  7. 优雅的键/值Cookie

  8. 自动解压

  9. Unicode响应体

  10. HTTP(S)代理支持

  11. 文件分块上传

  12. 流下载

  13. 连接超时

  14. 分块请求

  15. 支持.netrc

2.要求安装

请求是python的三方库,所以我们需要使用pip安装

pip install requests

或者通过二进制安装

git clone git://github.com/kennethreitz/requests.git cd python setup.py install

3.要求用例

常用的HTTP操作为GET和POST,其他不常用的操作可以参考官方文档或串口调用相应方法即可。

import requests# GET 请求response = requests.get("https://getman.cn/echo")print(response.text)# GET 构造header,cookie,参数请求headers = {    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',}cookie = {"user":"APython"}params  = {'my_name':'AL','name':'APython'}response=requests.get("https://getman.cn/echo",headers=headers,cookies=cookie,params=params)print(response.text)#POST 请求data = {'name': 'APython-post','age': 24,}response = requests.post("https://getman.cn/echo", data=data)print(response.text)

4.请求更多示例

import requests# 下载文件(一)小文件url = 'https://raw.githubusercontent.com/psf/requests/master/ext/ss.png'response = requests.get(url)with open('demo.png', 'wb') as f:    f.write(response.content)    # 下载文件(二)大文件file_url = "https://readthedocs.org/projects/python-guide/downloads/pdf/latest/"response = requests.get(file_url)with open("python.dpf", "wb") as pdf:    for chunk in response.iter_content(chunk_size=1024):        if chunk:            pdf.write(chunk)            # POST 提交数据返回结果url = 'https://api.github.com/some/endpoint'data = {'some': 'APython'}response = requests.post(url, data=data)print(response.text)#session 会话保持(会话对象可以跨请求保持某些参数)session = requests.session()session.get(url)session.post(url,data)

感谢你能够认真阅读完这篇文章,希望小编分享的"python中Requests库有什么用"这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

0