Demo源码:
# _*_ coding:utf-8 _*_
import urllib.request
"""python3 用的是urllib.request"""
def load_baidu():
# 指定要访问的url
url = 'http://www.baidu.com'
# 发送请求 返回服务器的相应对象
response = urllib.request.urlopen(url)
# 读取相应文件中的数据
data = response.read()
print(data)
print(type(data)) # <class 'bytes'>
# 互连网上 都是用二进制进行传输 所以我们读取的数据是bytes类型
# 处理数据时需要对接收的数据进行解码 解码城我们看得懂的编码进行处理
new_data = data.decode()
with open('python3_urllib.html','w+') as f:
f.write(new_data)
if __name__ == '__main__':
load_baidu()
运行后报错信息:
UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 28319: illegal multibyte sequence
解决方案
方法(1)、把Demo源码的第20行改为:
with open('python3_urllib.html','w+',encoding='utf-8') as f:
就可以正常运行喽
方法(2)、把Demo源码放到linux系统下的pycharm中运行 就不会报错。