【问题标题】:python getting unicode encode error when saving file保存文件时python得到unicode编码错误
【发布时间】:2020-01-12 02:27:23
【问题描述】:

我正在尝试从网页中获取文本,它会生成“回溯(最近一次通话最后一次): 文件“C:\Users\username\Desktop\Python\parsing.py”,第 21 行,在 textFile.write(str(results)) UnicodeEncodeError: 'cp949' 编解码器无法在位置 37971 编码字符 '\xa9': 非法多字节序列'

我已经搜索并尝试过 textFile.write(str(results).decode('utf-8')) 它没有属性错误。

import requests
import os
from bs4 import BeautifulSoup

outputFolderName = "output"

currentPath = os.path.dirname(os.path.realpath(__file__))
outputDir = currentPath + "/" +outputFolderName

r = requests.get('https://yahoo.com/')
soup = BeautifulSoup(r.text, 'html.parser')
results = soup.findAll(text=True)

try :
    os.mkdir(outputDir)
    print("output directory generated")
except :
    print("using existing directory")

textFile = open(outputDir + '/output.txt', 'w')
textFile.write(str(results))
textFile.close()

有没有办法将str(results)的编解码转换并正确保存??

python版本是3.7.3

【问题讨论】:

  • cp949编解码器从何而来?你能发布完整的堆栈跟踪吗?
  • @TomDalton Traceback(最近一次调用最后):文件“C:\Users\username\Desktop\Python\parsing.py”,第 21 行,在 textFile.write(str(results )) UnicodeEncodeError: 'cp949' codec can't encode character '\xa9' in position 37971: 非法多字节序列
  • 请在问题正文中包含回溯(使用标签下方的“编辑”链接)。另外:您使用的是哪个 Python 版本?从 Python 2 到 Python 3,str() 的含义发生了显着变化。
  • @Pitto 这是整个代码。也许是因为我输入了 url 'example.com'。你能再试试这个代码吗?我刚刚修改了。

标签: python unicode beautifulsoup


【解决方案1】:

请像本例一样指定编码

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import os
from bs4 import BeautifulSoup

outputFolderName = "output"

currentPath = os.path.dirname(os.path.realpath(__file__))
outputDir = currentPath + "/" +outputFolderName

r = requests.get('https://yahoo.com')
soup = BeautifulSoup(r.text, 'html.parser')
results = soup.findAll(text=True)

try :
    os.mkdir(outputDir)
    print("output directory generated")
except :
    print("using existing directory")

textFile = open(outputDir + '/output.txt', mode='w', encoding='utf8')
textFile.write(str(results))
textFile.close()

【讨论】:

  • 嗨@FlippingFlop!如果我的回答有用,请不要忘记投票和/或选择它作为答案。谢谢!
猜你喜欢
  • 2012-01-22
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多