我正在使用带有请求模块的 Anaconda Python 3.7 Jupyter Notebook 从网站抓取一些视频游戏数据。
游戏“Brütal Legend”有一个变音符号,并且在我正在抓取的网站上正确显示,但是当我通过请求模块获取数据时,它显示的特殊字符不再完整。例如,这就是我得到的:
野蛮传奇
这是我的代码的样子:
import requests
targetURL = 'https://www.url.com/redacted.php?query'
r = requests.get(targetURL)
page_source = r.text
print("raw page_source", page_source)
我该怎么做才能保留特殊字符,以便它在我的 Jupyter Notebook 的输出中正确显示?
您需要知道 Response 中的字符集Content-Type
,即使大多数网站使用 utf8。response.text
将使用默认编码 UTF8 ,因为它使用decode()
和响应默认编码是 None 。
注意:许多站点没有显示字符集,但它们可能使用 utf8。
http://docs.python-requests.org/en/master/api/?highlight=encod#requests.Response.encoding
那么为什么你得到的Brütal Legend
是你使用错误的编码将字节转换为字符串。你应该试试r.content.decode("ISO-8859-1")
一个简单的例子:
import requests
with requests.Session() as s:
utf_8 = s.get("https://en.wikipedia.org/wiki/Br%C3%BCtal_Legend")
#response charset is UTF8
print(utf_8.text[101:126])
print(utf_8.content.decode("utf8")[101:126])
print(utf_8.content[101:127].decode("ISO-8859-1"))
输出:
Brütal Legend - Wikipedia
Brütal Legend - Wikipedia
Brütal Legend - Wikipedia
编辑:
print("Brütal Legend".encode("ISO-8859-1").decode())
#Brütal Legend
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句