Ubuntu 線上無界面服務器 使用selenium chrome + headless

參考:https://blog.csdn.net/Felix__H/article/details/82840454

如果報錯:

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome version must be between 71 and 75

則應該先查看chrom版本,然後選擇合適的chromdriver

參考的錯誤指南:https://cloud.tencent.com/developer/article/1404558
一、安裝 selenium
 pip install selenium
https://pypi.org/project/selenium/

二、安裝 chromdriver
進入: 淘寶鏡像源  

https://npm.taobao.org/

下載 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
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章