在Python中打印beautifulsoup4 get\u text()时出现UnicodeEncodeError

2024-04-24 20:12:48 发布

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

我正在用Python运行一个非常简单的脚本,从URL获取数据:

import urllib2
from bs4 import BeautifulSoup

def get_data():

    response = urllib2.urlopen('http://www.p2016.org/photos15/summit/trump012415spt.html')
    html = BeautifulSoup(response, 'html.parser')
    text = html.get_text()
    return text


print get_data()

我一直收到这个错误信息:

PS C:\Users\Ben\pythonlearning\markov_chain> python fetch_data.py
Traceback (most recent call last):
  File "fetch_data.py", line 11, in <module>
    print get_data()
  File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\xa9' in position 22825: character maps to <undefined>

我试过:

  • 在没有print命令的情况下运行它,我没有得到任何错误
  • 让另一台计算机上的人运行完全相同的代码,而且它是有效的。你知道吗

Tags: textinpyimportdatagetreturnresponse
1条回答
网友
1楼 · 发布于 2024-04-24 20:12:48

这个错误与“让另一台计算机上的某个人运行完全相同的代码,并且它可以工作”之间的区别是由于CPython解释器的版本不同。你知道吗

python3标志着语言特性发生了显著的向后不兼容的变化,这就是为什么会出现这个错误。你知道吗

您可以通过在两个平台上运行此命令来确认差异:

python -c 'import sys; print(sys.version)'

相关问题 更多 >