1. 字符编码问题
在使用selenium处理中文网页或者网页标题是中文的时候,出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128),
1 from selenium import webdriver 2 import sys 3 4 print sys.getdefaultencoding() 5 6 driver = webdriver.PhantomJS() 7 driver.get("http://www.sogou.com") 8 data = driver.find_element_by_id('wrap').text 9 print data
字符串在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成其他编码
代码中字符串的默认编码与代码文件本身的编码一致。
如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。通常,在没有指定特定的编码方式时,都是使用的系统默认编码创建的代码文件
sou'gou网站的标题编码是utf-8,
所以使用decode就可以解决这个问题
print data.encode("utf8")
2. driver.get("http://www.sogou.com")
这个网址似乎必须带http://才有效果
不带的话,好像访问的是about:blank
可以使用driver.current_url 看一下网址是否设置正确
3. 安装selenium
直接使用pip安装包(python网站下载)安装的话,install selenium会报错,原因不明
但是使用easy_install安装pip之后,使用pip install selenium,很快成功