【问题标题】:'ascii' codec can't decode byte 0xcb while doing bs [duplicate]'ascii'编解码器在执行bs时无法解码字节0xcb [重复]
【发布时间】:2016-12-16 15:13:03
【问题描述】:

我从 Merriam-Webster 的 API 将 xml 页面保存在本地,让我给你 url: http://www.dictionaryapi.com/api/v1/references/collegiate/xml/apple?key=bf534d02-bf4e-49bc-b43f-37f68a0bf4fd

这是一个例子。 我从 url 中 urlretrieve 并将其保存为 xml 文件。

现在我想打开它,但出现了 UnicodeDecodeError。

我做到了:

page = open('test.xml')
bs = BeautifulSoup(page)

然后出现以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb

我试图使网址u'test.xml' 不起作用。

sys.getdefaultencoding() 'utf-8'

编码配置已经是utf-8,解决不了问题,还是谢谢指教。

【问题讨论】:

    标签: python xml file encoding beautifulsoup


    【解决方案1】:

    您需要将编码指定为 utf-8,即数据的编码方式,文件名与内部内容无关,因此以 u 为前缀来生成 unicode 字符串无济于事:

    import io
    with io.open('test.xml', encoding="utf-8") as page:
          bs = BeautifulSoup(page)
    

    【讨论】:

    • 谢谢!我尝试使用 pickle 模块,当我使用它时,它说我用完了 inpuy
    • @AlexZhang,你是怎么用泡菜的?
    • 等一下,我正在尝试……我会尽快解释
    • 这就是我对pickle所做的:htmlFile = urlopen(theUrl).read().decode('utf-8') with open(filePath, 'wb') as file: pickle. dump(htmlFile, file, pickle.HIGHEST_PROTOCOL) 我认为这可能是因为我将参数设置为 wb 以便将其存储为 btyes,无论如何接下来是: with open(filePath,'rb') as file: print( filePath,':',pickle.load(file)) return pickle.load(file) 所以当我尝试加载它时会说这种问题。而且无论我如何尝试打开它,将其解码为 utf-8,它都不起作用,因为 read() 时会发生同样的错误
    • 你为什么要用pickle来转储html?
    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 2011-06-29
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2013-08-20
    相关资源
    最近更新 更多