安裝chrome
創建yum源
# cd /etc/yum.repos.d/
# vim google-chrome.repo
創建yum源信息
[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
# yum -y install google-chrome-stable --nogpgcheck
chrome安裝路徑
使用上述步驟安裝完成之后,chrome的安裝路徑在/opt/google/chrome目錄下
安裝chromeDriver
查看chrome版本
# google-chrome -version
下載對應版本的chromeDriver
從https://npm.taobao.org/mirrors/chromedriver/查詢與chrome版本對應的chromeDriver版本,大版本對應即可,如當前chrome最新的版本是78.0.3904.97,只需要查找與78對應的chromeDriver版本即可。
找到對應的版本后,在linux上使用以下命令下載chromeDriver壓縮包:
# mkdir /usr/chromedriver
# cd /usr/chromedriver
# wget https://npm.taobao.org/mirrors/chromedriver/version/chromedriver_linux64.zip
version為chromeDriver的完整版本號
下載之后解壓壓縮包:
# unzip chromedriver_linux64.zip
給chromeDriver文件夾賦予權限:
# chmod +x /usr/chromedriver/chromedriver
安裝Xvfb
安裝說明
安裝此軟件的原因是在centos上,chromeDriver必須使用無頭模式,當有不使用無頭模式的需求時就需要安裝此軟件,否則chromeDriver無法正確啟動chrome
安裝Xvfb
# yum install Xvfb -y
# yum install xorg-x11-fonts* -y
在/usr/bin/目錄下創建xvfb-chrome文件
# vim /usr/bin/xvfb-chrome
在xvfb-chrome文件中輸入以下內容
#!/bin/bash
_kill_procs() {
kill -TERM $chrome
wait $chrome
kill -TERM $xvfb
}
# Setup a trap to catch SIGTERM and relay it to child processes
trap _kill_procs SIGTERM
XVFB_WHD=${XVFB_WHD:-1280x720x16}
# Start Xvfb
Xvfb :99 -ac -screen 0 $XVFB_WHD -nolisten tcp &
xvfb=$!
export DISPLAY=:99
chrome --no-sandbox --disable-gpu$@ &
chrome=$!
wait $chrome
wait $xvfb
添加執行權限:
# chmod +x /usr/bin/xvfb-chrome
查看當前的映射關系:
# ll /usr/bin/ | grep chrom
映射關系如下所示:
lrwxrwxrwx 1 root root 31 Nov 18 14:25 chrome -> /etc/alternatives/google-chrome
lrwxrwxrwx 1 root root 20 Nov 18 14:25 google-chrome -> /usr/bin/xvfb-chrome
lrwxrwxrwx 1 root root 32 Jun 28 18:39 google-chrome-stable -> /opt/google/chrome/google-chrome
-rwxr-xr-x 1 root root 422 Nov 18 14:24 xvfb-chrome
更改chrome啟動的軟連接:
# ln -s /etc/alternatives/google-chrome /usr/bin/chrome
# rm -rf /usr/bin/google-chrome
# ln -s /usr/bin/xvfb-chrome /usr/bin/google-chrome
此時再次查看映射關系,如下所示:
lrwxrwxrwx 1 root root 31 Nov 18 14:36 chrome -> /etc/alternatives/google-chrome
lrwxrwxrwx 1 root root 20 Nov 18 14:36 google-chrome -> /usr/bin/xvfb-chrome
lrwxrwxrwx 1 root root 32 Jun 28 18:21 google-chrome-stable -> /opt/google/chrome/google-chrome
-rwxr-xr-x 1 root root 422 Nov 18 14:36 xvfb-chrome
以上步驟操作完成后即可在centos環境下使用非無頭瀏覽器,此時chromeDriver創建時不能再添加以下參數:
options.addArguments("--headless")