您的位置:首页 > 运维架构 > Linux

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

2021-01-01 18:57 92 查看

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

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

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

centos7 安装 chrome

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

  • 配置 yum 源

在目录

/etc/yum.repos.d/
下新建文件:
google-chrome.repo

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

写入下面内容:

[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 (安装的是最新稳定版本)

yum -y google-chrome-stable --nogpgcheck

如下图显示安装成功:

  • 查看版本

找到 chrome 路径,做个软连接方便使用:

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

到此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

  • 安装 chrome

输入命令:

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 详情可以参考下面的文章:

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

安装 Chromedriver

下载对应版本的 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

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()

执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: