1. 程式人生 > >Mac下python+selenium【1】環境搭建

Mac下python+selenium【1】環境搭建

寫在最前面:

搞自動化測試呢有很大概率會用到selenium,其實用什麼語言都可以,這次先從python講起。其實在win下我已經用了很久了,今天講講Mac下的安裝。

首先是環境搭建,本文基於macOS Mojave作業系統,我用的是python3.6+pycharm,這個就不介紹了,然後我們來安裝selenium。

pip3 install selenium
Collecting selenium
  Downloading https://files.pythonhosted.org/packages/80/d6/4294f0b4bce4de0abf13e17190289f9d0613b0a44e5dd6a7f5ca98459853/selenium-3.141.0-py2.py3-none-any.whl (904kB)
    100% |████████████████████████████████| 911kB 11kB/s 
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from selenium) (1.23)
Installing collected packages: selenium
Successfully installed selenium-3.141.0

然後下載一個chromedriver,連結如下http://npm.taobao.org/mirrors/chromedriver/,自己挑選合適的對應的chrome的版本即可。

我的chrome版本是

我下的chromedriver版本是71.0.3578.33/

我按照win的習慣放在專案目錄下了。

 

接下來簡單測試一下:

from selenium import webdriver
import selenium

if __name__ == "__main__":
    driver = webdriver.Chrome()
    driver.get('https://www.baidu.com/')

不出意外的報錯了

Traceback (most recent call last):
  File "/Users/Arithmetic/PycharmProjects/AutoTest/FirstTest.py", line 5, in <module>
    driver = webdriver.Chrome()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
    self.service.start()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

新增chromedriver的路徑:

sudo vim .bash_profile

輸入密碼

export PATH=$PATH:ChromeDriver
esc
:
wq!
source .bash_profile

 

然後又報了另一個錯

Traceback (most recent call last):
  File "/Users/Arithmetic/PycharmProjects/AutoTest/FirstTest.py", line 5, in <module>
    driver = webdriver.Chrome()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
    self.service.start()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start
    stdin=PIPE)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
NotADirectoryError: [Errno 20] Not a directory: 'chromedriver'

嘗試將chromedriver放入

/usr/local/bin

成功!

其實我試過了,不新增路徑也可以。。。

 

 記得輸入完整的網址,不然貌似打不開。

今天只講環境搭建。

今天雙十一實際上只剁手了一件nike的羽絨服,原價1199,實付401,真**便宜,晚安各位~