Python中urllib.request模块的基本用法及示例
发布时间:2023-12-27 13:55:14
urllib.request 是Python中用于发送HTTP请求的模块,可以发送GET、POST等请求,并获取响应结果。以下是urllib.request模块的基本用法及示例:
1. 发送GET请求:
使用urllib.request模块的urlopen()方法发送GET请求,该方法接受一个URL字符串作为参数,并返回一个表示响应的对象。可以使用read()方法来读取响应内容。
示例代码:
import urllib.request
# 发送GET请求
response = urllib.request.urlopen('https://www.example.com')
# 读取响应内容
html = response.read()
# 打印响应内容
print(html)
2. 发送POST请求:
使用urllib.request模块的Request()方法构建一个请求对象,可以传递一个URL字符串和一个data参数,data参数是一个字典类型的数据,用于向服务器发送POST请求体数据。
示例代码:
import urllib.parse
import urllib.request
# 构建POST请求数据
data = {
'username': 'admin',
'password': '123456'
}
# 将POST数据转换为url编码格式
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
# 构建请求对象
request = urllib.request.Request(url='https://www.example.com', data=encoded_data, method='POST')
# 发送POST请求
response = urllib.request.urlopen(request)
# 读取响应内容
html = response.read()
# 打印响应内容
print(html)
3. 发送带有请求头的请求:
可以通过添加请求头信息来发送带有请求头的请求,可以使用urllib.request模块的Request()方法构建一个请求对象,并通过add_header()方法来添加请求头。
示例代码:
import urllib.request
# 构建请求对象
request = urllib.request.Request(url='https://www.example.com')
# 添加请求头信息
request.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')
# 发送带有请求头的GET请求
response = urllib.request.urlopen(request)
# 读取响应内容
html = response.read()
# 打印响应内容
print(html)
4. 发送带有代理的请求:
可以通过设置ProxyHandler来发送带有代理的请求,可以设置HTTP代理和HTTPS代理。
示例代码:
import urllib.request
# 构建代理处理器
proxy_handler = urllib.request.ProxyHandler({'http': 'http://localhost:8888', 'https': 'https://localhost:8888'})
# 构建Opener
opener = urllib.request.build_opener(proxy_handler)
# 安装Opener
urllib.request.install_opener(opener)
# 发送带有代理的GET请求
response = urllib.request.urlopen('https://www.example.com')
# 读取响应内容
html = response.read()
# 打印响应内容
print(html)
以上是urllib.request模块的基本用法及示例。除了上述示例中的方法外,urllib.request模块还提供了其他的方法和类,用于处理cookies、文件下载等功能,可以根据具体需求选择合适的方法和类来使用。
