原文?https://www.cyberlight.xyz/passage/python3-selenium-linux
最近嘗試在服務(wù)器端運(yùn)行selenium,做下此筆記,其間參考了大量相關(guān)教程,感謝每一位共享學(xué)習(xí)記錄的網(wǎng)友!
由于windows10使用的Chrome,我繼續(xù)嘗試在CentOS運(yùn)行,終于成功!以下是學(xué)習(xí)記錄:
環(huán)境:CentOS8, Python 3.6.8
一.CentOS上安裝Chrome
請確保身份為root,進(jìn)入CentOS終端,然后依次輸入
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install -y google-chrome-stable_current_x86_64.rpm
查看Chrome版本
/opt/google/chrome/chrome -version

PS: chrome卸載方法
yum autoremove -y google-chrome
之后,需要解決不能在root下運(yùn)行chrome的錯誤 。Chrome安裝的根目錄默認(rèn)在 /opt/google/chrome/ 。進(jìn)入CentOS終端,輸入
vi /opt/google/chrome/google-chrome
移動光標(biāo)到最下面,按下鍵盤的”i”,將 exec -a “$0” “$HERE/chrome” “$@” 后面加上 –user-data-dir –no-sandbox 。整條命令修改后為
exec -a “$0” “$HERE/chrome” “$@” –user-data-dir –no-sandbox
如圖,將下圖一改為下圖二


接著依次按鍵盤 “esc” + “:” + “wq” 保存并退出
二.安裝Chrome驅(qū)動
一定要根據(jù)Chrome版本號安裝驅(qū)動,由于我的Chrome版本為80.0.3987.132(版本一定要下對,否則Python運(yùn)行會報錯)。經(jīng)測試,我應(yīng)該下載官網(wǎng)的80.0.3987.16,而不是80.0.3987.106
電腦進(jìn)入Chrome驅(qū)動官網(wǎng)https://chromedriver.chromium.org/downloads


鼠標(biāo)右鍵點(diǎn)擊Linux版本,復(fù)制鏈接。(如,我的鏈接為https://chromedriver.storage.googleapis.com/80.0.3987.16/chromedriver_linux64.zip)
進(jìn)入Centos,切換至系統(tǒng)根目錄(注意,不是root根目錄)。輸入以下命令切換至Chrome安裝目錄
cd /opt/google/chrome
wget + 上面復(fù)制的鏈接( 如,我的鏈接為https://chromedriver.storage.googleapis.com/80.0.3987.16/chromedriver_linux64.zip)
wget https://chromedriver.storage.googleapis.com/80.0.3987.16/chromedriver_linux64.zip
解壓下載的zip
unzip chromedriver_linux64.zip
此時驅(qū)動已安裝完畢。
三.Python測試
在Linux下創(chuàng)建Python文件
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--no-sandbox') #讓Chrome在root權(quán)限運(yùn)行
chrome_options.add_argument('--disable-dev-shm-usage') #不打開圖形界面
chrome_options.add_argument('--headless') #瀏覽器不提供可視化頁面
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加載圖片, 提升速度
chrome_options.add_argument('--disable-gpu') #谷歌文檔提到需要加上這個屬性來規(guī)避bug
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/opt/google/chrome/chromedriver') #Chrome驅(qū)動的位置,此學(xué)習(xí)記錄中安裝到了Chrome程序根目錄,該路徑為絕對路徑
driver.get('https://www.baidu.com')
content = driver.page_source.encode('utf-8')
print(content)
如返回百度的html源碼,說明程序運(yùn)行正常,能盡情在Linux使用selenium爬蟲了
PS: 運(yùn)行selenium如遇錯誤 error: DevToolsActivePort file doesn’t exist ,很可能是安裝的Chrome驅(qū)動版本不對!
評論區(qū)歡迎分享你的學(xué)習(xí)記錄和解決方法哦