【发布时间】:2017-05-10 15:33:30
【问题描述】:
这是我的代码:
soup = bs4.BeautifulSoup(res.text, "html.parser")
linkElems = soup.select('.r a')
for i in range(len(linkElems)):
t = linkElems[i].findAll(text=True)
print(t)
这给了我错误:
Traceback (most recent call last):
File "C:\Path\Python\code.py", line 17, in <module>
print(t)
File "C:\Program Files\Python 3.5\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in position 9: character maps to <undefined>
print(t) 行给了我错误。
我正在使用 Python 3 和 Beautiful Soup 4。我怎样才能摆脱这个错误?
【问题讨论】:
-
顺便说一句,你可以在这里使用
.get_text():[elm.get_text() for elm in soup.select('.r a')]。 -
总是显示有问题的完整错误消息(Traceback)。它显示了哪条线有问题。
-
您可以添加指向源数据的链接。
-
您在
unicode中有文本,但print()始终必须将其转换为控制台/终端/cmd.exe/powershell 使用的编码 - 如果终端没有通知 python 它使用什么编码然后print() 对文本进行编码有问题。您可以手动编码文本,即。print(t.encode('utf-8') but it may depend on system which you use - Linux mostly needutf-8` 但 Windows 可能需要win1250或其他。
标签: python python-3.x beautifulsoup python-3.5