W3C
在编写微博爬虫的时候,稍微学习了一下网页编码的知识,主要来自于 W3C 官方文档的 5.2.2 小节。
To sum up, conforming user agents must observe the following priorities when determining a document’s character encoding (from highest priority to lowest):
- An HTTP “charset” parameter in a “Content-Type” field.
- A META declaration with “http-equiv” set to “Content-Type” and a value set for “charset”.
- The charset attribute set on an element that designates an external resource.
首先看 http 头信息中的 Content-Type 字段,如果没有的话,会查看 Meta 信息,如果还没有的话,会查看一些外部资源的信息,比如css或者JavaScript的charset字段。
如果以上信息依然不能确定编码的话,就采用默认的 ISO-8859-1 字符集去解析网页。
gb2312 页面解析
在爬取 “珠海市人力资源和社会保障局” 的网站的时候,遇到中文编码 gb2312,使用 iconv-lite 对其进行处理,代码如下:
1 | ; |