requests爬取中文网站的字符编码问题

    这两天在一些门户网站使用requests爬数据的时候,发现打印或者保存到文件中的中文显示为Unicode码,看着十分不爽快,于是就必须网上找了一下相关问题。其实,弄明白了解决也很简单了
   比如,爬取凤凰网

response= requests.get("http://www.ifeng.com/")

   我们都知道response有textcontent这两个property,它们都是指响应内容,但是又有区别。我们从doc中可以看到:

   text的doc内容为:

Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using ``chardet``.
The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property.

   而content的doc内容为:

Content of the response, in bytes.

   其中text是unicode码,content是字节码,我们获取到的响应内容的字符编码只取决于HTTP headers,也就是我们查看网页源码时<head>标签下<meta>标签中charset指定的字符编码方式,例如:

<meta http-equiv="content-type" content="text/html;charset=utf-8">

   因此,当我们使用text属性获取html内容出现unicode码时,我们可以通过设置字符编码response.encoding,来使之匹配网页源码中指定的字符编码,这样打印输出就不会很奇怪了。

import requests

response = requests.get("http://www.ifeng.com/")
response.encoding = "utf-8" #手动指定字符编码为utf-8
print(response.text)

   有兴趣的童鞋可以试试没有指定字符编码或者指定其他字符编码的效果。有不懂的欢迎留言讨论!

   另外,我们使用python内置的文件操作函数打开文本文件(不是二进制文件,注意区别)时,默认使用的platform dependent的字符编码进行编解码文本文件,比如Windows中使用的是Ascii,Linux中使用的是utf-8,当然,我们再open()的时候可以通过encoding指定字符编码,例如:

open(fileName,"r",encoding="utf-8")

以上就是关于python在爬取中文网页时遇到的一些小问题,记录一下,以便帮助自己和大家。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章