ubuntu中如何安装selenium+chrome(headless)无界面浏览器?

selenium是一个Web的自动化测试工具,它可以根据我们的指令,让浏览器自动加载页面,获取需要的数据,甚至页面截屏,或者判断网站上某些动作是否发生。但是它自身不带浏览器,不支持浏览器的功能,因此它需要与第三方浏览器结合在一起才能使用。当selenium升级到3.0之后,对不同的浏览器驱动进行了规范。如果想使用selenium驱动不同的浏览器,必须单独下载并设置不同的浏览器驱动。本文以Chrome浏览器为例,需要安装驱动chromedriver

一、安装selenium

sudo pip3 install selenium

二、安装Chrome浏览器

  • 安装依赖

    sudo apt-get install libxss1 libappindicator1 libindicator7
  • 下载安装包

    wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb #执行命令,下载稳定版Chrome浏览器
  • 安装

    sudo dpkg -i google-chrome*.deb
    sudo apt-get install -f

三、安装chromedriver

  • 查看Chrome浏览器版本

    google-chrome --version   #执行该命令获取当前Chrome浏览器版本号
  • 下载对应版本chromedriver

    wget -N http://chromedriver.storage.googleapis.com/浏览器版本号(比如88.0.4324.96)/chromedriver_linux64.zip
  • 安装unzip,用于解压缩

    sudo apt-get install unzip
  • 解压缩

    unzip chromedriver_linux64.zip
  • 移动chromedriver位置

    sudo mv chromedriver /usr/local/share/chromedriver
  • 建立软链接-----后续创建driver时就不需要再指定executable_path这个参数

    sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver

四、测试(访问百度)

In [1]: from selenium import webdriver #导入webdriver

In [2]: from selenium.webdriver.chrome.options import Options

In [3]: option = Options()

In [4]: option.add_argument('--headless') #指定参数选项,创建无界面浏览器

In [5]: driver = webdriver.Chrome(options=option)

In [6]: driver.get('https://www.baidu.com/') #访问百度

In [7]: driver.current_url #获取当前网站的url
Out[7]: 'https://www.baidu.com/'

In [8]: driver.title #获取网页标题
Out[8]: '百度一下,你就知道'

In [9]: driver.quit() #关闭浏览器

 

posted @ 2021-02-01 16:25  eliwang  阅读(2646)  评论(0编辑  收藏  举报