1.导入库
import urllib.request
2.访问网络步骤
//第一种方式
1.创建request对象
2.打开网络获得response对象
url = "" #访问地址
data = {} #数据
header = {} #请求头
request = urllib.request.Request(url) #(url,data,header)
response = urllib.request.urlopen(request)
print(request)
print(response)
//第二种方式
url = "" #访问地址
response = urllib.request.urlopen(url)
print(response)
3.response对象
//1 获得response流 -- 字节流必须使用这种方式
html = response.read()
//2 把response 流 编码为 utf8
html = response.read().decode('utf-8')
//3 response 的信息
response.info()
//4 response 的code
response.code
//5 response 的url
response.url
4.request 对象
//1 request的类型
request.type
// 2 request的头
request.unredirected_hdrs
//3 request获得host
request.host
//4 request获得完整url
request.full_url
//5 request 添加header
req.add_header('','')
5.代理服务器
# 准备url
url = ""
# 准备代理服务器
proxys = {'http':'180.103.131.65:808'}
# 创建代理
proxy_support = urllib.request.ProxyHandler(proxys)
# 创建一个opener
opener = urllib.request.build_opener(proxy_support)
# 安装opener
urllib.request.install_opener(opener)
# 创建request
request = urllib.request.Request(url)
# 打开url获得response
response = urllib.request.urlopen(request)
# 获得返回信息
html = response.read().decode('utf-8')
print(html)