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加上即可。

 

然后就可以正常的運行腳本啦~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM