Python中的HTTP客户端库:urllib和http.client的比较
发布时间:2024-01-07 08:06:41
Python中有多个HTTP客户端库可以用于发送HTTP请求和处理响应。其中两个比较常用的库是urllib和http.client。下面是对它们的比较和使用示例。
1. urllib库
urllib是Python标准库中的一个模块,提供了一些用于处理URL的工具函数和类。它包含了四个子模块:urllib.parse、urllib.request、urllib.error和urllib.robotparser。
(1)urllib.parse:用于解析和操作URL。
使用示例:
from urllib.parse import urlparse url = 'http://www.example.com/path?a=1&b=2#fragment' parsed = urlparse(url) print(parsed.scheme) # 输出:http print(parsed.netloc) # 输出:www.example.com print(parsed.path) # 输出:/path print(parsed.query) # 输出:a=1&b=2 print(parsed.fragment) # 输出:fragment
(2)urllib.request:用于发送HTTP请求和处理响应。
使用示例:
from urllib.request import urlopen
response = urlopen('http://www.example.com')
html = response.read().decode('utf-8')
print(html)
(3)urllib.error:用于处理HTTP请求过程中的错误。
使用示例:
from urllib.request import urlopen
from urllib.error import HTTPError
try:
response = urlopen('http://www.example.com/404')
except HTTPError as e:
print('HTTP Error:', e.code)
(4)urllib.robotparser:用于解析和处理robots.txt文件。
使用示例:
from urllib.robotparser import RobotFileParser
rp = RobotFileParser()
rp.set_url('http://www.example.com/robots.txt')
rp.read()
if rp.can_fetch('myuseragent', '/somepage'):
print('Allowed')
else:
print('Not allowed')
2. http.client库
http.client是Python标准库中的一个模块,提供了一个可以用于发送HTTP请求和处理响应的类。它是基于底层的socket模块实现的。
使用示例:
import http.client
conn = http.client.HTTPSConnection('www.example.com')
conn.request('GET', '/')
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data.decode('utf-8'))
以上是对urllib和http.client库的比较和使用示例。两个库功能类似,都可以用于发送HTTP请求和处理响应,选择使用哪个库可以根据具体的需求和个人偏好来决定。
