Centos7服务器(无GUI)作UI自动化(python+selenium+chrome)

平时作web UI 自动化都是在window系统有界面操做的,如今想在本身的服务器上跑自动化,遇到的问题有:html

  • 没有相应的浏览器
  • 使用的是Linux系统(无GUI)
  • 执行的时候看不到界面

针对以上问题,主要仍是浏览器的问题,把浏览器安装上就行,并且如今的浏览器也支持无界面(headless)执行了,这里选择 chrome 浏览器。python

centos7 安装 chrome

【方法一:经过 yum 直接下载安装】linux

  • 配置 yum 源

在目录 /etc/yum.repos.d/下新建文件: google-chrome.repoweb

vi /ect/yum.repos.d/google-chrome.repochrome

写入下面内容: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
  • 安装 chrome

经过下面命令下载安装 Google-chrome (安装的是最新稳定版本)bootstrap

yum -y google-chrome-stable --nogpgcheck

以下图显示安装成功:centos

img

  • 查看版本

找到 chrome 路径,作个软链接方便使用:api

which google-chrome-stable
ln -s xxx /bin/chrome

image-20210101162113299

到此chrome安装完成!浏览器

【方法二:下载 rpm 包安装】

  • 下载 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

image-20210101163501319

  • 安装 chrome

输入命令:

yum -y localinstall google-chrome-stable-87.0.4280.88-1.x86_64.rpm

image-20210101163816769

  • 查看版本

找到 chrome 路径,作个软链接方便使用:

which google-chrome-stable
ln -s xxx /bin/chrome

image-20210101164021757

到此 chrome 安装成功!

注意:无GUI的Linux系统咱们启动 chrome 是会报错的,程序执行的时候须要使用无头模式(headless)

若是你想打开这种带界面的程序,咱们可使用 X11-forwarding 详情能够参考下面的文章:

本地显示Linux服务器的GUI程序

安装 Chromedriver

下载对应版本的 chromedriver:

下载地址:https://chromedriver.storage.googleapis.com/index.html

image-20210101165747655

能够经过网页下载到本地,解压后上传到服务器,也能够直接命令下载:

wget https://chromedriver.storage.googleapis.com/87.0.4280.88/chromedriver_linux64.zip

而后解压到对应的路径:

unzip chromedriver_linux64.zip

赋予执行权限:

chmod +x ./chromedriver

python 代码测试

Linux 默认就有 python 环境,在使用 selenium 以前咱们须要提早安装下对应的包文件,这样才能完成后续的编码,这里使用 pip 来管理包文件。

  • 安装 pip

下载 pip :

wget https://bootstrap.pypa.io/get-pip.py

执行安装:

python get-pip.py
  • 安装 selenium
pip install selenium
  • python 测试代码
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()

执行结果:

image-20210101171934861

相关文章
相关标签/搜索