什么是一个很好,可靠的短途方式来获取网页的字符集? [英] What is a nice, reliable short way to get the charset of a webpage?

查看:88
本文介绍了什么是一个很好,可靠的短途方式来获取网页的字符集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点惊讶的是,使用Python获取网页的字符集非常复杂。我错过了一条路吗? HTTPMessage有很多功能,但不是这个。

I'm a bit surprised that it's so complicated to get a charset of a webpage with Python. Am I missing a way? The HTTPMessage has loads of functions, but not this.

>>> google = urllib2.urlopen('http://www.google.com/')
>>> google.headers.gettype()
'text/html'
>>> google.headers.getencoding()
'7bit'
>>> google.headers.getcharset()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: HTTPMessage instance has no attribute 'getcharset'

所以你必须得到标题,拆分它。两次。

So you have to get the header, and split it. Twice.

>>> google = urllib2.urlopen('http://www.google.com/')
>>> charset = 'ISO-8859-1'
>>> contenttype = google.headers.getheader('Content-Type', '')
>>> if ';' in contenttype:
...     charset = contenttype.split(';')[1].split('=')[1]
>>> charset
'ISO-8859-1'

这是一个令人惊讶的步骤基本功能。我错过了什么吗?

That's a surprising amount of steps for such a basic function. Am I missing something?

推荐答案

你看过这个吗?

如何下载任何(!)网页,其中包含正确的字符集python?

这篇关于什么是一个很好,可靠的短途方式来获取网页的字符集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆