如何正确编码网站请求响应中的德语字符?

2024-05-29 03:52:26 发布

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

我想从中提取数据转让标的。对于获取数据,我使用请求库。但是不管我使用什么编码,德语的特殊字符都没有被正确解析。你知道吗

站点在报头中使用UTF-8作为编码,但是请求中的自动编码输出了错误的特殊字符。通过比较我发现,当使用UTF-8时,r.text看起来和r.content完全一样。你知道吗

所以我读了很多关于编码的书(是的,我想我现在懂Unicode了;-))并尝试了不同的请求编码-下面是我的测试代码:

import requests

link = 'https://www.transfermarkt.de/fc-bayern-munchen/kader/verein/27/saison_id/2017'        
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'


r=requests.get(link, headers={"User-Agent":user_agent})

print('---------------------------------CONTENT----------')
print(r.content[4500:5000])

r.encoding = 'UTF-8'
print('-------------------------------TEXT UTF8----------')
print(r.text[4500:5000])

r.encoding = 'iso-8859-1'
print('--------------------------------TEXT iso-8859-1----------')
print(r.text[4500:5000])

这将产生以下输出:

-----------------------------------------CONTENT----------
FC Bayern M├╝nchen - Kader im Detail 17/18" />
<link rel="stylesheet" type="text/css" 
href="https://tmssl.akamaized.net//css/stylesheets/menue.css?lm=1556636907" />
<link rel="stylesheet" type="text/c
-----------------------------------------TEXT iso-8859-1----------
FC Bayern München - Kader im Detail 17/18" />
<link rel="stylesheet" type="text/css" 
href="https://tmssl.akamaized.net//css/stylesheets/menue.css?lm=1556636907" />
<link rel="stylesheet" type="text/c
-----------------------------------------TEXT UTF8----------
Bayern M├╝nchen - Kader im Detail 17/18" />
<link rel="stylesheet" type="text/css" 
href="https://tmssl.akamaized.net//css/stylesheets/menue.css?lm=1556636907" />
<link rel="stylesheet" type="text/css"

如你所见,摘录中没有正确显示“München”的“ü”。有人知道我能做些什么吗?你知道吗


Tags: texthttps编码typelinkisocssutf

热门问题