平時作web UI 自動化都是在window系統有界面操做的,如今想在本身的服務器上跑自動化,遇到的問題有:html
針對以上問題,主要仍是瀏覽器的問題,把瀏覽器安裝上就行,並且如今的瀏覽器也支持無界面(headless)執行了,這裏選擇 chrome 瀏覽器。python
【方法一:經過 yum 直接下載安裝】linux
在目錄 /etc/yum.repos.d/
下新建文件: google-chrome.repo
web
vi /ect/yum.repos.d/google-chrome.repo
chrome
寫入下面內容:shell
[google-chrome] name=google-chrome baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch enabled=1 gpgcheck=1 gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
經過下面命令下載安裝 Google-chrome (安裝的是最新穩定版本)bootstrap
yum -y google-chrome-stable --nogpgcheck
以下圖顯示安裝成功:centos
找到 chrome 路徑,作個軟鏈接方便使用:api
which google-chrome-stable ln -s xxx /bin/chrome
到此chrome安裝完成!瀏覽器
【方法二:下載 rpm 包安裝】
能夠到這個網站找對應的安裝包:
https://pkgs.org/download/google-chrome-stable
這裏下載當前最新版本,具體下載地址:
https://dl.google.com/linux/chrome/rpm/stable/x86_64/google-chrome-stable-87.0.4280.88-1.x86_64.rpm
能夠經過網址下載到本地後上傳Linux系統,也能夠在Linux系統中直接下載,輸入命令:
wget https://dl.google.com/linux/chrome/rpm/stable/x86_64/google-chrome-stable-87.0.4280.88-1.x86_64.rpm
輸入命令:
yum -y localinstall google-chrome-stable-87.0.4280.88-1.x86_64.rpm
找到 chrome 路徑,作個軟鏈接方便使用:
which google-chrome-stable ln -s xxx /bin/chrome
到此 chrome 安裝成功!
注意:無GUI的Linux系統咱們啓動 chrome 是會報錯的,程序執行的時候須要使用無頭模式(headless)
若是你想打開這種帶界面的程序,咱們可使用 X11-forwarding 詳情能夠參考下面的文章:
下載對應版本的 chromedriver:
下載地址:https://chromedriver.storage.googleapis.com/index.html
能夠經過網頁下載到本地,解壓後上傳到服務器,也能夠直接命令下載:
wget https://chromedriver.storage.googleapis.com/87.0.4280.88/chromedriver_linux64.zip
而後解壓到對應的路徑:
unzip chromedriver_linux64.zip
賦予執行權限:
chmod +x ./chromedriver
Linux 默認就有 python 環境,在使用 selenium 以前咱們須要提早安裝下對應的包文件,這樣才能完成後續的編碼,這裏使用 pip 來管理包文件。
下載 pip :
wget https://bootstrap.pypa.io/get-pip.py
執行安裝:
python get-pip.py
pip install selenium
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--headless') # 使用無頭模式執行chrome chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') # 這個必定要加,不加Chrome啓動報錯 # 這裏chromedriver的路徑,寫你的對應路徑,最方便就是放在同一個路徑,也能夠配置環境變量。 driver = webdriver.Chrome(executable_path='./chromedriver',chrome_options=chrome_options) driver.get("https://www.baidu.com") print driver.page_source driver.close()
執行結果: