urllib是python提供的标准模块,可以发送http请求
urllib.Request:构造请求
urllib.request.urlopen:发送请求
url = "http://www.baidu.com"
# 构造headers
headers = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"}
# 构造请求体
data = {
"type":"AUTO",
"i":"i love python",
"doctype":"json",
}
# 构造请求
request = urllib.request.Request(url, data = data, headers = headers)
# 发送请求
response = urllib.request.urlopen(request)
print(response.read())
response.read():获取响应
获取响应的html字符串,bytes类型
#获取响应
response.read()
【demo10】urllib请求百度首页
import urllib.request
url = 'http://www.baidu.com'
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print(response.read())