linux下搭建selenium环境

记录在linux服务器上搭建selenium环境,用于Python爬虫

安装chrome浏览器

Centos7

  1. 添加 yum 信息

    1
    vim /etc/yum.repos.d/google-chrome.repo

    向文件中添加以下内容:

    1
    2
    3
    4
    5
    6
    [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
  2. 安装chrome

    Google官方源安装:

    1
    yum -y install google-chrome-stable

    Google官方源可能在中国无法使用,导致安装失败或者在国内无法更新,可以添加以下参数来安装:  

    1
    yum -y install google-chrome-stable --nogpgcheck
  3. 添加 chrome 到环境变量中

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

    1
    2
    which google-chrome-stable
    ln -s xxx /bin/chrome # xxx为chrome可执行文件路径

Ubuntu 18.04

1
2
3
4
5
6
7
8
9
10
#先安装各种依赖:
sudo apt-get -f install
#32位下载与安装命令:
wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb
sudo dpkg -i google-chrome-stable_current_i386.deb
#64位下载与安装命令:
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
#查看版本
google-chrome --version

如果出现dpkg安装错误,再输入命令sudo apt-get -f install,之后重新使用dpkg安装。

下载webdriver

​ 以chromedriver为例,下载地址 ,选择对应版本的driver

Python代码:

1
2
3
4
5
6
7
8
9
from selenium import webdriver
chromeOptions = webdriver.ChromeOptions()
# 加载无窗口浏览器
chromeOptions.add_argument('--headless')
#chromeOptions.add_argument('--disable-dev-shm-usage')
chromeOptions.add_argument('--lang=en_US')
# 以根用户打身份运行Chrome,使用-no-sandbox标记重新运行Chrome,禁止沙箱启动
chromeOptions.add_argument('--no-sandbox')
driver = webdriver.Chrome(options=chromeOptions, executable_path=driver_path) #driver_path为driver路径