📅  最后修改于: 2023-12-03 15:19:36.223000             🧑  作者: Mango
Python是一门优秀的编程语言,它的许多库可以方便地完成HTTP请求的操作。本教程将介绍Python中最常用的两个HTTP请求库requests和urllib,帮助你快速地发送各种类型的HTTP请求。
requests库可以使用pip进行安装:
pip install requests
使用requests库发送HTTP请求非常简单,以下是向GitHub API发送一个GET请求的示例:
import requests
response = requests.get('https://api.github.com')
print(response.status_code)
print(response.content)
输出:
200
b'{"current_user_url": "https://api.github.com/user", "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}", "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}", "emo...
这里我们向GitHub API发送了一个GET请求,并打印了返回的状态码和响应内容。
requests库支持各种HTTP请求类型,包括GET、POST、PUT、DELETE、HEAD、OPTIONS和PATCH。
以下是向url发送POST请求的一个示例:
import requests
url = 'http://httpbin.org/post'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.json())
输出:
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.25.1",
"X-Amzn-Trace-Id": "Root=1-609de4db-3b4dbe4f7df015172f726050"
},
"json": null,
"origin": "114.114.114.114",
"url": "http://httpbin.org/post"
}
我们通过向httpbin发送POST请求,并在请求体中传递了键值对,最终得到了一个json格式的响应。
requests库的响应对象有很多属性和方法可以让你方便地处理返回的数据。以下是一些示例:
import requests
response = requests.get('https://api.github.com')
# 响应状态码
print(response.status_code)
# 响应头
print(response.headers)
# 响应内容
print(response.content)
# 响应解码为字符串
print(response.text)
# 响应解码为json格式
print(response.json())
Python自带的urllib库也可以用于HTTP请求。该库的核心模块是urllib.request,可以用于发送各种类型的HTTP请求。
以下是向GitHub API发送一个GET请求的一个示例:
from urllib.request import urlopen
response = urlopen('https://api.github.com')
print(response.status)
print(response.read())
输出:
200
b'{"current_user_url": "https://api.github.com/user", "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}", "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}", "emo...
以下是向url发送POST请求的一个示例:
from urllib.request import Request, urlopen
import urllib.parse
url = 'http://httpbin.org/post'
data = urllib.parse.urlencode({'key1': 'value1', 'key2': 'value2'}).encode('ascii')
req = Request(url, data)
response = urlopen(req)
print(response.read())
输出:
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.9",
"X-Amzn-Trace-Id": "Root=1-609de51b-10c4bc7d529f2be558552e7c"
},
"json": null,
"origin": "114.114.114.114",
"url": "http://httpbin.org/post"
}
urllib.request模块可以用于发送各种类型的HTTP请求,包括GET、POST、PUT、DELETE、HEAD、OPTIONS和PATCH。以下是向url发送POST请求的一个示例:
from urllib.request import Request, urlopen
import urllib.parse
url = 'http://httpbin.org/post'
data = urllib.parse.urlencode({'key1': 'value1', 'key2': 'value2'}).encode('ascii')
req = Request(url, data)
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3')
response = urlopen(req)
print(response.read())
urlopen函数返回的响应对象有很多属性和方法可以让你方便地处理返回的数据。以下是一些示例:
from urllib.request import urlopen
import urllib.parse
response = urlopen('https://api.github.com')
# 响应状态码
print(response.status)
# 响应头
print(response.info())
# 响应内容
print(response.read())
# 响应解码为字符串
print(response.read().decode())
# 响应解码为json格式
import json
json.loads(response.read().decode('utf-8'))
本教程介绍了Python中两个常用的HTTP请求库requests和urllib。使用这些库可以方便地完成各种类型的HTTP请求操作,并处理返回的数据。如果你对HTTP请求感兴趣,请继续学习并掌握这些重要的库。