平时作web UI 自动化都是在window系统有界面操做的,如今想在本身的服务器上跑自动化,遇到的问题有:html
针对以上问题,主要仍是浏览器的问题,把浏览器安装上就行,并且如今的浏览器也支持无界面(headless)执行了,这里选择 chrome 浏览器。python
【方法一:经过 yum 直接下载安装】linux
在目录 /etc/yum.repos.d/
下新建文件: google-chrome.repo
web
vi /ect/yum.repos.d/google-chrome.repo
chrome
写入下面内容:shell
[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 (安装的是最新稳定版本)bootstrap
yum -y google-chrome-stable --nogpgcheck
以下图显示安装成功:centos
找到 chrome 路径,作个软链接方便使用:api
which google-chrome-stable ln -s xxx /bin/chrome
到此chrome安装完成!浏览器
【方法二:下载 rpm 包安装】
能够到这个网站找对应的安装包:
https://pkgs.org/download/google-chrome-stable
这里下载当前最新版本,具体下载地址:
https://dl.google.com/linux/chrome/rpm/stable/x86_64/google-chrome-stable-87.0.4280.88-1.x86_64.rpm
能够经过网址下载到本地后上传Linux系统,也能够在Linux系统中直接下载,输入命令:
wget https://dl.google.com/linux/chrome/rpm/stable/x86_64/google-chrome-stable-87.0.4280.88-1.x86_64.rpm
输入命令:
yum -y localinstall google-chrome-stable-87.0.4280.88-1.x86_64.rpm
找到 chrome 路径,作个软链接方便使用:
which google-chrome-stable ln -s xxx /bin/chrome
到此 chrome 安装成功!
注意:无GUI的Linux系统咱们启动 chrome 是会报错的,程序执行的时候须要使用无头模式(headless)
若是你想打开这种带界面的程序,咱们可使用 X11-forwarding 详情能够参考下面的文章:
下载对应版本的 chromedriver:
下载地址:https://chromedriver.storage.googleapis.com/index.html
能够经过网页下载到本地,解压后上传到服务器,也能够直接命令下载:
wget https://chromedriver.storage.googleapis.com/87.0.4280.88/chromedriver_linux64.zip
而后解压到对应的路径:
unzip chromedriver_linux64.zip
赋予执行权限:
chmod +x ./chromedriver
Linux 默认就有 python 环境,在使用 selenium 以前咱们须要提早安装下对应的包文件,这样才能完成后续的编码,这里使用 pip 来管理包文件。
下载 pip :
wget https://bootstrap.pypa.io/get-pip.py
执行安装:
python get-pip.py
pip install selenium
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--headless') # 使用无头模式执行chrome chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') # 这个必定要加,不加Chrome启动报错 # 这里chromedriver的路径,写你的对应路径,最方便就是放在同一个路径,也能够配置环境变量。 driver = webdriver.Chrome(executable_path='./chromedriver',chrome_options=chrome_options) driver.get("https://www.baidu.com") print driver.page_source driver.close()
执行结果: