【发布时间】: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