ubuntu中如何安裝selenium+chrome(headless)無界面瀏覽器?


selenium是一個Web的自動化測試工具,它可以根據我們的指令,讓瀏覽器自動加載頁面,獲取需要的數據,甚至頁面截屏,或者判斷網站上某些動作是否發生。但是它自身不帶瀏覽器,不支持瀏覽器的功能,因此它需要與第三方瀏覽器結合在一起才能使用。當selenium升級到3.0之后,對不同的瀏覽器驅動進行了規范。如果想使用selenium驅動不同的瀏覽器,必須單獨下載並設置不同的瀏覽器驅動。本文以Chrome瀏覽器為例,需要安裝驅動chromedriver

一、安裝selenium

sudo pip3 install selenium

二、安裝Chrome瀏覽器

  • 安裝依賴

    sudo apt-get install libxss1 libappindicator1 libindicator7
  • 下載安裝包

    wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb #執行命令,下載穩定版Chrome瀏覽器
  • 安裝

    sudo dpkg -i google-chrome*.deb
    sudo apt-get install -f

三、安裝chromedriver

  • 查看Chrome瀏覽器版本

    google-chrome --version   #執行該命令獲取當前Chrome瀏覽器版本號
  • 下載對應版本chromedriver

    wget -N http://chromedriver.storage.googleapis.com/瀏覽器版本號(比如88.0.4324.96)/chromedriver_linux64.zip
  • 安裝unzip,用於解壓縮

    sudo apt-get install unzip
  • 解壓縮

    unzip chromedriver_linux64.zip
  • 移動chromedriver位置

    sudo mv chromedriver /usr/local/share/chromedriver
  • 建立軟鏈接-----后續創建driver時就不需要再指定executable_path這個參數

    sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver

四、測試(訪問百度)

In [1]: from selenium import webdriver #導入webdriver

In [2]: from selenium.webdriver.chrome.options import Options

In [3]: option = Options()

In [4]: option.add_argument('--headless') #指定參數選項,創建無界面瀏覽器

In [5]: driver = webdriver.Chrome(options=option)

In [6]: driver.get('https://www.baidu.com/') #訪問百度

In [7]: driver.current_url #獲取當前網站的url
Out[7]: 'https://www.baidu.com/'

In [8]: driver.title #獲取網頁標題
Out[8]: '百度一下,你就知道'

In [9]: driver.quit() #關閉瀏覽器

 


免責聲明!

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



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