问题描述
我正在尝试抓取这个NREGA Website,其中包含印地语(即梵文)脚本中的数据。结构非常容易刮擦。但是,当我使用request / urllib获取HTML代码时,印地语文本已转换为一些乱码。文本在网站的代码源中显示得很好。
content = requests.get(URL).text
站点中的'1पी'被解析为'1 \ xe0 \ xa4 \ xaa \ xe0 \ xa5 \ x80 \ xe0 \ xa4 \ x8f \ xe0 \ xa4 \ xb8'我尝试导出到csv。
解决方法
服务器的响应未在其Content-Type标头中指定字符集,因此请求assumes that the page is encoded as ISO-8859-1(拉丁1)。
>>> r = requests.get('https://mnregaweb4.nic.in/netnrega/writereaddata/citizen_out/funddisreport_2701004_eng_1314_.html')
>>> r.encoding
'ISO-8859-1'
实际上,页面已被编码为UTF-8,正如我们通过检查响应的apparent_encoding
属性所知道的:
>>> r.apparent_encoding
'utf-8'
或通过实验
>>> s = '1 \xe0\xa4\xaa\xe0\xa5\x80 \xe0\xa4\x8f\xe0\xa4\xb8'
>>> s.encode('latin').decode('utf-8')
'1 पी एस'
可以通过解码响应的content
属性来获得正确的输出:
>>> html = r.content.decode(r.apparent_encoding)