UnicodeEncodeError:“ascii”编解码器无法编码字符“\u2013”

2024-03-29 00:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在macOS上使用python3.6和sublimetext3。当我运行脚本时,我在标题中得到了错误。我已经尽了我在网上找到的一切办法来解决这个问题,但我仍然有同样的问题,没有解决的想法。这是我的剧本:

import requests
import subprocess
import time

from bs4 import BeautifulSoup

response = requests.get("https://news.ycombinator.com")
soup = BeautifulSoup(response.content, "html.parser")
for story in soup.find_all(class_="storylink"):
    title = story.get_text()
    print(title + "\n")

完整的stacktrace是:

^{pr2}$

问题在于title变量,是的,我知道它包含一些python不知道如何打印的unicode字符(因为它使用ASCII??)。在

我的工作是,以13\xc2\xa0comments的形式打印unicode字符。但我想把它打印成unicode字符。。。在

如果你运行脚本,你必须有一些“运气”遇到这个问题,因为不是每个标题都包含一个unicode字符。另外,say命令只在macOS上存在-如果在其他操作系统上测试,请将其删除。在

编辑:为了好玩,我尝试在终端中执行脚本,但在那里我没有得到错误!所以这和崇高的文本3有关。。。在

编辑2:如果我加上sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())就可以了


Tags: import脚本编辑标题gettitleresponse错误