mac下selenium+python环境搭建
selenium2+python的环境搭建主要需要python和selenium
1.python
mac下自带了python,可以查看版本。当然可以选择安装其它版本的python。
2.selenium
在mac自带的终端里输入 sudo easy_install selenium即可完成安装
通过以上两步就完成了最基本的环境安装。一般选择firefox作为自动化测试对应的默认浏览器,当然也可以使用其它浏览器。
以firefox为例,我们可以执行以下python脚本,测试selenium能否正常使用。
1 from selenium import webdriver 2 import time 3 dr = webdriver.Firefox() 4 time.sleep(5) 5 print'Browser will be closed' 6 dr.quit() 7 print'Browser is close'
执行如上脚本的时候遇到如下报错:
Traceback (most recent call last): File "/Users/xxx/Documents/selenium_py/inittest/test.py", line 3, in <module> dr = webdriver.Firefox() File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__ self.service.start() File "/Library/Python/2.7/site-packages/selenium/webdriver/common/service.py", line 81, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. [Finished in 0.1s with exit code 1]
原因是使用的firefox版本是56.0,对于比较高版本的firefox浏览器,需要在下载对应的驱动geckodriver。将下载的驱动放到自己需要的目录下。
修改原脚本如下所示,将具体的驱动位置作为入参。
from selenium import webdriver import time dr = webdriver.Firefox(executable_path = '/Users/xxx/Documents/selenium_py/geckodriver/geckodriver') #dr = webdriver.Chrome(executable_path = '/Users/xxx/Documents/selenium_py/chromdriver/chromedriver') print'Browser will be closed' dr.quit() print'Browser is close'
对于其它浏览器只需要在官网http://www.seleniumhq.org/download/ 下载对应的驱动即可。
在脚本里加上了驱动位置以后还是出现了报错
Traceback (most recent call last): File "/Users/xxx/Documents/selenium_py/inittest/test.py", line 3, in <module> dr = webdriver.Firefox(executable_path = '/Users/xxx/Documents/selenium_py/geckodriver/geckodriver') File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__ self.service.start() File "/Library/Python/2.7/site-packages/selenium/webdriver/common/service.py", line 102, in start raise WebDriverException("Can not connect to the Service %s" % self.path) selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service /Users/xxx/Documents/selenium_py/geckodriver/geckodriver [Finished in 38.3s with exit code 1]
解决这个问题在/etc/hosts文件中将127.0.0.1 localhosts加上即可。
然后就可以正常的运行脚本啦~