zoukankan      html  css  js  c++  java
  • 问题: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'))




  • 相关阅读:
    c/cpp枚举练习
    数据类型的标识
    引用变量
    cocos2dx 3.3 笔记
    希望获取到页面中所有的checkbox怎么做?
    如何判断某变量是否为数组数据类型?
    驼峰函数写法
    trim()函数
    js 获取页面可视区域宽高
    全屏滚动插件
  • 原文地址:https://www.cnblogs.com/fly2wind/p/6426319.html
Copyright © 2011-2022 走看看