1. 程式人生 > >Ubuntu 線上無介面伺服器 使用selenium chrome + headless

Ubuntu 線上無介面伺服器 使用selenium chrome + headless

 

一、安裝 selenium

 pip install selenium

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

二、安裝 chromdriver

進入: 淘寶映象源  下載 chromdriver

 

一般都是下載當時最新版本  現在我下載的是 2.42 。 可以檢視 notes.txt 檔案,看chrome 和ChromDriver 兩者相對應的相容版本

下載  chromedriver_linux64.zip

解壓 得到 chromedriver檔案

遠端 把chromedirver 檔案放到線上伺服器 /usr/bin/ 下。

 

三、Ubuntu線上伺服器 安裝chrome(重點)

命令列  執行下面的命令

sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*.deb    # Might show "errors", fixed by next line
sudo apt-get install -f
google-chrome --version      # 檢視版本

chrome瀏覽器歷史版本

四.測試

寫一個 test.py  測試

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox') # 這個配置很重要
client = webdriver.Chrome(chrome_options=chrome_options, executable_path='/home/chromedriver')    # 如果沒有把chromedriver加入到PATH中,就需要指明路徑
 
client.get("https://www.baidu.com")
print (client.page_source.encode('utf-8'))

client.quit()

成功打印出  網頁內容 ,那就ok了  !!!!

 

如果沒有下面這個配置

options.add_argument('--no-sandbox')

會出現下面  報錯資訊

selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist