温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python中Requests库有什么用

发布时间:2021-11-25 15:21:12 来源:亿速云 阅读:577 作者:小新 栏目:大数据

这篇文章主要介绍了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 <requests目录>
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)

python中Requests库有什么用

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库有什么用”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI