问题:python3 使用beautifulSoup时,出错UnicodeDecodeError: 'gbk' codec …….

想将html文件转为纯文本,用Python3调用beautifulSoup

超简单的代码一直出错,用于打开本地文件:

 
  1. from bs4 import BeautifulSoup
  2. file = open('index.html')
  3. soup = BeautifulSoup(file,'lxml')
  4. print (soup)

出现下面的错误

UnicodeDecodeError : ‘gbk’ codec can’t decode byte 0xff in position 0: illegal multibyte sequence

beautifulSoup不是自称可以解析各种编码格式的吗?为什么还会出现解析的问题???

搜了很多关于beautifulSoup的都没有解决,突然发现,如果把代码写成

 
  1. from bs4 import BeautifulSoup
  2. file = open('index.html')
  3. str1 = file.read() # 错误出在这一行!!!
  4. soup = BeautifulSoup(str1,'lxml')
  5. print (soup)

原来如此! 问题出在文件读取而非BeautifulSoup的解析上!!

好吧,查查为什么文件读取有问题,直接上正解,同样四行代码

 
  1. from bs4 import BeautifulSoup
  2. file = open('index.html','r',encoding='utf-16-le')
  3. soup = BeautifulSoup(file,'lxml')
  4. print (soup)

然后soup.get_text()得到标签中的文字

其它

如果文件中存在多种编码而且报错,可以采用下面这种方式忽略,没测试–

 
  1. soup = BeautifulSoup(content.decode('utf-8','ignore'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值