import urllib.requesturl = 'https://www.baidu.com/'# 指定自定义请求头
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36'
}# 创建带有自定义请求头的请求对象
custom_request = urllib.request.Request(url=url, headers=headers)# 发送请求并获取响应
response = urllib.request.urlopen(custom_request)# 读取并打印响应内容(从字节解码为字符串)
print(response.read().decode('utf-8'))
运行结果