python下使用selenium的坑

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,很快成功

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值