天天看點

Python + Selenium:環境搭建

進行Selenium的webdriver操作,首先當然是搭建環境了。今天介紹一下Python + Selenium的webdriver環境搭建

1.Python

Mac電腦上是已經預裝了Python2的,但現在主流都推薦Python3,我們最好還是使用Python3來進行腳本的編寫。

  • Mac

方法1:

終端輸入

brew install python3 
           

就自動安裝了

方法2:

https://www.python.org/downloads/mac-osx/ 進入官網下載下傳安裝包後安裝即可

  • Linux

Linux下也大部分自帶Python2的版本,介紹一下如何下載下傳安裝Python3。

1.安裝依賴環境

yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel
           

2.安裝wget(如果你的Linux沒有安裝wget,已安裝略過)

yum install -y wget
           

3.下載下傳Python(注意想下載下傳的版本,這裡示範下載下傳Python3.6.1)

wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz
           

4.解壓安裝包

tar -zxvf Python-3.6.1.tgz
           

5.編譯安裝

安裝之前,先确定安裝的位置,比如我想安裝在/url/local下,我可以先建立一個檔案夾

mkdir -p /url/local/python3
           

然後把解壓的python移動過來(當然也可以先建立好檔案夾再在該檔案夾下解壓)

mv Python-3.6.1 .
           

進入Python檔案夾,安裝,編譯

cd Python-3.6.1
./configure --prefix=/usr/local/python3
           

make實際編譯源代碼,并生成執行檔案,接着執行make install指令

make
make install
           

6.建立一個軟連接配接

ln -s /usr/local/python3/bin/python3 /usr/bin/python3
           

7.配置PATH(新安裝的路徑加入Path中)

# vim ~/.bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin:/usr/local/python3/bin
export PATH
           

記得按ESC,輸入:wq儲存并修改哦。然後使其生效

# source ~/.bash_profile
           

8.檢查一下是否安裝成功

python3 -v
pip3 -v
           

兩個指令輸入完顯示版本即安裝成功

  • Windows

下載下傳

https://www.python.org/downloads/windows/

進入官網下載下傳對應版本

配置環境變量

Path裡面把Python3的檔案夾加入,如 ;C:\Users\naver\AppData\Local\Programs\Python

Selenium

Python安裝成功後,我們來安裝Selenium,由于我們安裝了Python3,使用pip時也用Python3的pip來進行安裝(一般預設為pip3)

  • Mac
sudo pip3 install -U selenium
           
  • Linux
pip3 install -U selenium
           
  • Windows
pip3 install -U selenium
           

也可以去官網下載下傳

https://pypi.org/project/selenium/

浏覽器

Selenium支援的浏覽器很多,一般浏覽器主流有Firefox,Chrome等,這裡推薦Firefox或Chrome,請自行下載下傳并安裝(注意浏覽器安裝成功後最好關閉自動更新)

浏覽器插件

想要Selenium能在浏覽器中使用,需要下載下傳安裝相應浏覽器的插件。

https://seleniumhq.github.io/selenium/docs/api/py/index.html#

下載下傳解壓後,需要把驅動(如chromedriver.exe)檔案放到環境變量Path所在的目錄下。

FireBug、FirePath

FireBug和FirePath是Firefox中的必備插件了,在管理器中即可搜到。使用這兩個插件可以快速檢視定位的Xpath和CSS,友善在寫腳本的時候定位元素。但火狐浏覽器57.0版本更新之後,不再支援firebug和firepath這兩個插件了,在這裡就不詳細說明了。