python库requests常用方法


Python的requests库是一个非常强大的HTTP客户端库,它允许您轻松发送HTTP请求并处理响应。下面是一个简单的教程,向您展示如何使用requests库发送HTTP请求。

安装 requests:

要使用requests库,您需要先安装它。可以使用pip包管理器来安装它。在命令行中运行以下命令:

pip install requests

#清华源加速安装
pip install requests -i https://pypi.douban.com/simple
发送 GET 请求

下面是一个使用requests库发送GET请求的例子:

import requests

response = requests.get('https://www.example.com')

print(response.text)
发送POST请求

要发送一个POST请求,您可以使用requests库的post函数。以下是一个使用POST请求的例子:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://test.org/post', data=payload)

print(response.text)

这个例子发送一个POST请求到https://test.org/post,并在请求正文中包含一个payload字典。requests库将自动将payload编码为表单数据,并将其作为请求正文发送。

发送文件
import requests

url = 'https://test.org/post'
files = {'file': open('file.txt', 'rb')}

response = requests.post(url, files=files)

print(response.text)

这个例子将一个名为file.txt的文件上传到https://test.org/post,并打印出响应内容。

下载图片
import requests

url = "https://test.com/abc.jpg"
response = requests.get(url)
with open("logo.jpg", "wb") as f:
    f.write(response.content)
设置请求头(Header)
import requests

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'
}
url = 'https://www.example.com'
response = requests.get(url, headers=headers)
print(response.text)

这个例子设置了一个User-Agent请求头,将其值设置为Mozilla/5.0。

设置请求超时时间
response = requests.get(url, timeout=15)
使用代理
proxies = {'http':'http://127.0.0.1:8081','https':'http://127.0.0.1:8081'}
response = requests.get(url, proxies=proxies)
处理响应
  • response.status_code: 返回码
  • response.headers: 响应头
  • response.content: 响应内容,字节形式
  • response.text: 响应内容,文本形式
  • response.request.headers: 请求响应头
  • response.json():如果响应正文是JSON格式,则将其解析为Python对象。

以下是一个处理响应的例子:

import requests

response = requests.get('https://www.example.com')

print('Status code:', response.status_code)
print('Headers:', response.headers)
print('Content (text):', response.text)

  • 📢博客主页:https://blog.csdn.net/qq233325332
  • 📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
  • 📢本文由 陌北v1 原创,首发于 CSDN博客🙉
  • 📢停下休息的时候不要忘了别人还在奔跑,希望大家抓紧时间学习,全力奔赴更美好的生活✨
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大恩子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值