问题:
使用webdriver中获取网页数据流的时候,然后print driver.find_element_by_id('').text,出现如下错误
UnicodeEncodeError: 'gbk' codec can't encode character u'\ue60a' in position 20: illegal multibyte sequence
原因:
对于此Unicode字符,需要print出来的话,由于本地系统是Windows中的cmd(linux无此情况出现,请放心食用),默认codepage是CP936,即GBK的编码,所以python解释器需要先将上述的Unicode字符编码为GBK,然后再在cmd中显示出来。
但是由于包含一些GBK中无法显示的字符,导致此时提示“’gbk’ codec can’t encode”的错误的。
方法1:
在对unicode字符编码时,添加ignore参数,忽略无法无法编码的字符,这样就可以正常编码为GBK了。
print str.encode("GBK", 'ignore');
方法2:
将其转换为GBK编码的超集GB18030 (即,GBK是GB18030的子集):
print str.encode("GB18030");