UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

在使用selenium处理中文网页或者网页标题是中文的时候,出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128),web

1 from selenium import webdriver
2 import sys
3 
4 print sys.getdefaultencoding()
5 
6 driver = webdriver.PhantomJS()
7 driver.get("http://www.douban.com")
8 
9 print driver.title

字符串在Python内部的表示是unicode编码,所以,在作编码转换时,一般须要以unicode做为中间编码,即先将其余编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另外一种编码。

decode的做用是将其余编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的做用是将unicode编码转换成其余编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

所以,转码的时候必定要先搞明白,字符串str是什么编码,而后decode成unicode,而后再encode成其余编码

代码中字符串的默认编码与代码文件自己的编码一致。

douban网站的标题编码是gb2312,
因此使用decode就能够解决这个问题网站

print driver.title.encode("gb2312")编码

 为何会报错“UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)”?本文就来研究一下这个问题。
字符串在Python内部的表示是unicode编码,所以,在作编码转换时,一般须要以unicode做为中间编码,即先将其余编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另外一种编码。

decode的做用是将其余编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的做用是将unicode编码转换成其余编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

所以,转码的时候必定要先搞明白,字符串str是什么编码,而后decode成unicode,而后再encode成其余编码

代码中字符串的默认编码与代码文件自己的编码一致。

如:s='中文'

若是是在utf8的文件中,该字符串就是utf8编码,若是是在gb2312的文件中,则其编码为gb2312。这种状况下,要进行编码转换,都须要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其余编码。一般,在没有指定特定的编码方式时,都是使用的系统默认编码建立的代码文件。spa

相关文章
相关标签/搜索