所在位置:

在 centos 中部署 selenium 项目

selenium是非常强大的,使用 selenium 可以做一些自动化的测试或者爬虫,如果有一些网站不能使用正常的方式爬取,试试 selenium 说不定就能解决,我们使用 python3 来部署 selenium,下面是 selenium 在 centos 中部署的步骤:

安装 python3 和 pip3

  • 安装相关依赖
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel gcc
  • 下载 python3.7.4 并安装
wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz
tar -zxvf Python-3.7.4.tgz
cd Python-3.7.4 && ./configure prefix=/usr/local/python3
make && make install
ln -s /usr/local/python3/bin/python3  /usr/bin/python3
  • 安装 pip3
ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3

安装 Chrome 浏览器

  • 添加 google 的 repo 源,在 /etc/yum.repos.d/ 目录添加一个 google.repo 文件,内容如下:
[google]
name=Google-x86_64
baseurl=http://dl.google.com/linux/rpm/stable/x86_64
enabled=1
gpgcheck=0
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
  • 安装
sudo yum update -y
sudo yum install google-chrome-stable -y
yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts -y

安装 Chrome 浏览器的驱动

  • 查看 chrome 浏览器的版本
google-chrome --version
  • 到 http://chromedriver.storage.googleapis.com/index.html,下载相对应的版本
wget http://chromedriver.storage.googleapis.com/112.0.5615.49/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
chmod +x /usr/bin/chromedriver

测试 selenium 是否可用

  • 初始化 selenium_demo 的项目
mkdir selenium_demo
cd selenium_demo
touch test_selenium.py
  • 添加 test_selenium.py 的内容如下:
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options


if __name__ == "__main__":
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')
    options.add_argument('--window-size=2560,1600')
    driver = Chrome(options=options)
    driver.get('https://www.baidu.com/')
    print(driver.page_source)
    driver.save_screenshot("test.png")
    driver.close()
    driver.quit()
  • 建立 python3 的 env3 环境,并安装 selenium 库
python3 -m venv env3
source env3/bin/activate
pip3 install selenium
  • 运行并测试
python test_selenium.py

参考链接

【上一篇】使用 docker 部署 verdaccio 搭建私有仓库

【下一篇】在 centos 中安装 nginx

相关文章