使用bs4提取本地的html文件时,发生编码错误。如下
#-*- coding = utf-8 -*- #@Time : 2022/2/20 17:46 #@File : bs4数据解析.py #@software : PyCharm #bs4数据解析 #数据解析原理 1.标签定位,2.提取标签,标签属性中存储的数据值 #bs4 1.标签定位 1.实例化一个BeautifulSoup对象,并将页面源码加载到该对象中 #2.通过调用BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取 #环境安装:install bs4 pip install lxml from bs4 import BeautifulSoup #对象实例化 #1.将本地的HTML文档中的数据加载到该对象中 #将本地html加载带该对象中 fp =open('./sogou.html','r',encoding='utf-8') soup = BeautifulSoup(fp,'lxml') fp.close() print(soup) #2.将互联网上获取的页面源码加载到该对象中
发生报错UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 7819: illegal multibyte
解决办法:
import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码 fp =open('./sogou.html','r',encoding='utf-8') soup = BeautifulSoup(fp,'lxml') fp.close() print(soup.decode('utf-8'))