1. 程式人生 > >Selenium Python 學習教程(一)

Selenium Python 學習教程(一)

安裝python
開啟 Python官網,找到“Download”, 在其下拉選單中選擇自己的平臺(Windows/Mac),一般的Linux平臺已經自帶的Python,所以不需要安裝,通過開啟“終端” ,輸入“python”命令來驗證。

如果你是第一次接觸Python,一定會迷惑Python為什麼會提供Python2.x 和 Python3.x兩個版本?那麼,直接使用Python3.x的最新版本就好了。因為Python2.x預計到2020年不在維護。

如果你是Windows平臺使用者,會遇到一個版本為什麼會提供多種個下載連結。例如:

Python 3.6.1 - 2017-03-21
Download Windows x86 web-based installer
Download Windows x86 executable installer
Download Windows x86 embeddable zip file
Download Windows x86-64 web-based installer
Download Windows x86-64 executable installer
Download Windows x86-64 embeddable zip file
Download Windows help file
x86 只支援32位的系統; x86-64 支援64位的系統。 web-based 在安裝的過程中需要聯網;executable 可執行檔案(.exe)方式安裝;embeddable zip file 嵌入式版本,可以整合到其它應用中。

注意:在安裝的過程中需要勾選:“Add Python 3.x to PATH” , 如果沒有勾選,需要在安裝完成之後,將Python的安裝目錄(如:C:\Python36)新增到環境變數PATH下面。

開啟Windows命令提示符(cmd)/ Linux終端輸入:

C:\Users\name>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.

安裝selenium
首先,在Windows命令提示符(cmd)/ Linux終端輸入:

C:\Users\name>pip

Usage:
pip [options]

Commands:
install Install packages.
download Download packages.
uninstall Uninstall packages.
freeze Output installed packages in requirements format.
list List installed packages.
show Show information about installed packages.
check Verify installed packages have compatible dependencies.
……

確保pip命令可用,如果提示“pip不是內部或外部命令”,需要將將pip的安裝目錄(如:C:\Python36\Scripts)新增到環境變數PATH下面。

接下來通過pip命令安裝Selenium:

C:\Users\name>pip install selenium
Collecting selenium
Downloading selenium-3.4.3-py2.py3-none-any.whl (931kB)
26% |████████ | 245kB 576kB/s eta 0:00:02
27% |█████████ | 256kB 570kB/s eta 0:00:02
28% |██████████ | 266kB 536kB/s eta 0:00:0
29% |███████████ | 276kB 530kB/s eta 0:00:0
30% |████████████ | 286kB 586kB/s eta 0:00:0
……

測試
開啟一款Python編輯器,預設Python自帶的IDLE也行。建立 baidu.py檔案,輸入以下內容:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(‘https://www.baidu.com’)

print(driver.title)

driver.quit()