centos7下安装无头浏览器(headless Chrome)

selenium是当前流行的WEB自动化工具,它可以启动本地浏览器,访问网页,模拟点击操作等,在自动化测试和网络爬虫中非常有用。

一般开发环境都是有图形界面的,所以本地只要安装普通浏览器就行了,但是在服务器环境是没有图形界面的,所以需要安装无头浏览器,所谓无头浏览器就是没有图形界面,但仍能实现浏览器访问网页,渲染网页的功能。

第一步,添加repo

使用vim工具新建google.repo文件

vi /etc/yum.repos.d/google.repo

然后按 i 进入编辑模式,拷贝以下代码,按ESC再输入:wq保存退出

[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

第二步,安装chrome

更新yum源,安装chrome

yum update
yum install google-chrome-stable

第三步,安装驱动chromedriver

先查看chrome版本,再安装对应驱动

google-chrome --version

下载对应驱动

wget -N http://chromedriver.storage.googleapis.com/浏览器版本号(比如88.0.4324.96)/chromedriver_linux64.zip

如果显示404说明没对应版本,比如我的版本是105.0.5195.102就没有,那就打开http://chromedriver.storage.googleapis.com/

 然后搜索105.0.5195找最相近的版本,可以发现有105.0.5195.52,那就下载这个版本

安装unzip工具

yum install unzip

解压

unzip chromedriver_linux64.zip

建立软链接

ln -s chromedriver /usr/bin/chromedriver

在任意目录输入chromedriver --version有正常返回,说明安装成功了

使用JAVA代码测试

public class TestMain {
    public static void main(String[] args) {
        //驱动地址,如果驱动放在/local/bin中则不需要
        //System.setProperty("webdriver.chrome.driver","/usr/local/chromedriver");
        ChromeOptions chromeOptions= new ChromeOptions();
        //2.设置为headless模式(必须)  如果不写代表不打开浏览器,反之
        chromeOptions.addArguments("--headless");
        // 禁用沙箱   linux环境
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        //3.设置浏览器窗口打开大小 (非必须)
        chromeOptions.addArguments("--window-size=1920,1080");
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("http://www.baidu.com");
        String title=driver.getTitle();
        System.out.println(title);
        driver.quit();
    }
}

maven代码,引入依赖,打包成可执行jar包

  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.3.3.RELEASE</version>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>cn.cloud.TestMain</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>

打成可执行Jar包后放到linux服务器,通过java -jar xxx执行,打印以下信息说明成功了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值