Unicode解析

2024-04-19 11:52:15 发布

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

from urllib.request import urlopen
html = urlopen("http://www.google.com/").read().decode('utf-8').replace("preview","")
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        if any(c.isalpha() for c in data):
            print(data)
MyHTMLParser().feed(html)
input()

所以我试图制作一个程序,它可以查看网站并保存数据,然后显示HTML的主要数据。这可以完美地与google一起工作,也可以在空闲状态下工作,但是任何其他在cmd中使用unicode字符(如\u2605(黑星)或\u00A9(版权)的站点都会出错。此错误会立即关闭cmd窗口。回溯是:

"UnicodeEncodeError: 'charmap' codec can't encode character '\u2122' in position 8: character maps to (undefined)"

image

我可以在网站上找到很多(replace),但是我相信有一个简单的方法可以转换它,这样它就可以阅读它,或者直接用“”替换它们。在


Tags: 数据infromimportcmddata网站html
1条回答
网友
1楼 · 发布于 2024-04-19 11:52:15

看了之后:UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

按照建议2,解决方案似乎涉及导入sys并用系统标准输出编码和errors='ignore'

html = urlopen("http://www.google.com/").read().encode(sys.stdout.encoding, errors='replace').decode('utf-8')`

你可能需要再解码一次…我不太确定,因为我还没有在我的机器上设置这个问题

相关问题 更多 >