我正在用python3.8编写代码,以便使用selenium从html源代码中获取一些文本。
我从page_source
得到了类似的内容( html_source
太长了,所以我只显示了print()
输出的焦点部分):
html_source = browser.page_source
print(html_source)
>>> \u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4
但我的预期产出是:
print(html_source)
>>> 免費資源網路社群
我试过这样做:
html_source.encode(‘utf-8’)
# but the result is same
print(html_source)
>>> \u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4
这似乎是因为html_source
中的Unicode是原始字符串。那么,如何将原始Unicode转换为预期的输出呢?
我对编码很陌生,而且对文本的编码解码也很混乱。我将感谢您能提供的任何帮助。
补编:
# I discover that r’’ string will give a similar result as above
html_source = r”\u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4”
print(html_source)
>>> \u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4
# while if the string is normal
html_source = “\u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4”
print(html_source)
>>> 免費資源網絡社群
发布于 2021-03-17 18:12:48
Python 3:
s = r'\u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4'
print(s.encode('utf-8').decode('unicode-escape'))
Python 2
s = r'\u514d\u8cbb\u8cc7\u6e90\u7db2\u8def\u793e\u7fa4'
print (s.decode('unicode-escape').encode('utf-8'))
发布于 2021-03-17 17:01:22
试着使用
utf8string = unicodestring.encode("utf-8")
https://stackoverflow.com/questions/66677687
复制相似问题