程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 基础教程十五之 Python 使用requests库发送http请求

hfteth 2025-03-20 15:03:47 技术文章 30 ℃

前言

在现代网络应用中,HTTP(HyperText Transfer Protocol)协议是客户端与服务器之间数据传输的核心。作为Python开发者,了解和掌握如何发送和处理HTTP请求至关重要。无论你是开发Web应用、爬虫,还是进行API集成,本文都将从基础到高级,逐步引导你成为HTTP请求处理的高手。

Python http请求

在Python中,进行HTTP请求通常有几种方式。最常用的库是requests和urllib。下面将分别介绍如何使用这两个库来发送HTTP请求。

使用requests库

首先,你需要安装requests库(如果你还没有安装的话):

pip3 install requests
edy@edydeMacBook-Pro bin % pip3 install requests
Requirement already satisfied: requests in /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages (2.32.3)
Requirement already satisfied: charset-normalizer<4,>=2 in /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages (from requests) (3.4.1)
Requirement already satisfied: idna<4,>=2.5 in /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages (from requests) (3.10)
Requirement already satisfied: urllib3<3,>=1.21.1 in /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages (from requests) (2.3.0)
Requirement already satisfied: certifi>=2017.4.17 in /Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages (from requests) (2025.1.31)

[notice] A new release of pip is available: 24.3.1 -> 25.0.1
[notice] To update, run: pip3 install --upgrade pip

然后,你可以使用以下方式来发送HTTP请求:

发送GET请求

requests.get(url, params=None, **kwargs)

  • url: 请求的URL。
  • params: (可选)要在URL中附加的查询参数。
  • **kwargs: 其他可选参数,例如 headers、timeout 等。

参数说明:若需要传请求参数,可直接在 url 后面添加,也可以在调用get()方法时通过关键字params传入,需要注意的是params需要传入dict(字典)类型。

下面以请求百度为例,发送get请求:

import requests

# 发送GET请求
response = requests.get(url='http://www.baidu.com/s?wd=requests模块')
print(response.text)

# 通过params传参
response2 = requests.get(url='http://www.baidu.com/s', params={"wd": "requests模块"})
print(response.status_code)		# 打印状态码

发送POST请求

requests.post(url, data=None, json=None, **kwargs)

  • url: 请求的URL。
  • data: (可选)要发送的表单数据。
  • json: (可选)要作为 JSON 发送的数据。
  • **kwargs: 其他可选参数,例如 headers、timeout 等。

参数说明:可传dict类型也可传json类型,dict类型使用关键字data传参,json类型则为使用关键字json传参。若无需传参可不传。

下面以请求企业微信群机器人为例,发送post请求:

import requests

# 发送POST请求
path = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-12345-5678-9876-test'
header = {
    "Content-Type": "application/json"
}
json = {
    "msgtype": "text",
    "text": {
        "content": "hello world"
    }
}
response = requests.post(url = path, json = json, headers=header)
print(response.status_code)		# 打印状态码
print(response.json())

打印信息如下:

200
{'errcode': 0, 'errmsg': 'ok'}

获取响应数据

常见的属性:

response.status_code:获取响应状态码

response.cookies:获取cookies

response.headers:获取头部信息

response.url:获取url

response.text:自动识别文本中的编码格式进行解码,但有时候不准确,会出现乱码

response.content.decode('utf-8'):response.content,获取字节流的数据,进行decode解码,默认是utf8

response.json():json方法可以将json字符串转换成对应的python类型的数据,接口返回的数据99%都是json类型的

使用连接池

建立HTTP连接是一个耗时的操作,为了减少连接的开销,你可以使用连接池来复用已有的连接。在requests库中,你可以通过设置Session对象来启用连接池。

import requests

path = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c615f575-5dbf-4dde-aa16-e5db014782de'
header = {
    "Content-Type": "application/json"
}
json = {
    "msgtype": "text",
    "text": {
        "content": "hello world"
    }
}

session = requests.session()
response = session.post(url = path, json = json, headers=header)
print(response.status_code)		# 打印状态码
print(response.json())

session.close()

Tags:

最近发表
标签列表