#!/usr/bin/env Python
# -*- coding: gbk -*-
#上面这句很重要,声明了python文件编码,常用的编码方式有utf8/utf-8/gbk/gb2312,没有此句会报错,
#SyntaxError: Non-ASCII character '\xc9' in file request1.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
#python自带的编码格式为ASCII
import requests
import sys
reload(sys)
sys.setdefaultencoding('gbk') #本句指明本程序的编码方式,若没有此句,报的错误是UnicodeEncodeError: 'ascii' codec can't encode characters in position 294-302: ordinal not in range(128)
print sys.getdefaultencoding() #当选择utf-8时,由于网页数据的编码格式是gbk,却以utf-8解码,因而网页的中文数据会显示乱码,而本程序自带的中文正常显示(utf-8编码与解码)
s="中文"
print s
r=requests.get("http://www.baidu.com")
print(str(r.status_code)+"\n")
print(r.encoding)
print(r.apparent_encoding)
r.encoding="utf-8"
print("抓取的网页内容为:"+str(r.text))
# -*- coding: gbk -*-
#上面这句很重要,声明了python文件编码,常用的编码方式有utf8/utf-8/gbk/gb2312,没有此句会报错,
#SyntaxError: Non-ASCII character '\xc9' in file request1.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
#python自带的编码格式为ASCII
import requests
import sys
reload(sys)
sys.setdefaultencoding('gbk') #本句指明本程序的编码方式,若没有此句,报的错误是UnicodeEncodeError: 'ascii' codec can't encode characters in position 294-302: ordinal not in range(128)
print sys.getdefaultencoding() #当选择utf-8时,由于网页数据的编码格式是gbk,却以utf-8解码,因而网页的中文数据会显示乱码,而本程序自带的中文正常显示(utf-8编码与解码)
s="中文"
print s
r=requests.get("http://www.baidu.com")
print(str(r.status_code)+"\n")
print(r.encoding)
print(r.apparent_encoding)
r.encoding="utf-8"
print("抓取的网页内容为:"+str(r.text))
print("网页头信息内容为:"+str(r.headers)+"\n")
程序编码格式为gbk,而网页的为iso(猜测header头信息得到)与utf-8(按网页内容得到),只有当程序编码为gbk且r.encoding="utf-8",才能正常显示
其中缘由待更