zoukankan      html  css  js  c++  java
  • Java之selenium实现模拟谷歌浏览器操作

    仅此记录下使用过程,入门水平。

    环境准备

    基本依赖

    1.去google下载对应浏览器版本和系统的驱动(其它浏览器同理去对应的下载即可)

     2.maven项目依赖包

    seleniumhq是基本API,如果没导入guava 可能会报错
           <!-- seleniumhq -->
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>3.141.59</version>
            </dependency>
            <!--https://mvnrepository.com/artifact/com.google.guava/guava -->
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>27.1-jre</version>
            </dependency>

    简单示例

    import cn.hutool.core.util.ObjectUtil;
    import util.FileHelper;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.springframework.core.io.ClassPathResource;
    
    import java.util.List;
    
    public class SeleniumTest {
        private static WebDriver.Navigation navigation;
    
        public static void main(String[] args) throws InterruptedException {
            //登陆测试模板
            test1();
    
            //test5();
        }
    
        /**
         * 模拟输入并点击登陆的测试模板
         */
        public static void test1() throws InterruptedException {
            //首先要注册系统属性,如果是firefox浏览器,需要设置webdriver.gecko.driver(注意不是webdriver.firefox.driver)
            //再指定驱动放置的路径。
            System.setProperty("webdriver.chrome.driver","/xxx/driver/chromedriver");
            //加一些设置
            ChromeOptions options = new ChromeOptions();
           //谷歌的一个限制 要关闭掉
            options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
            //控制不弹出浏览器
            options.setHeadless(false);
            //创建WebDriver对象
            WebDriver driver = new ChromeDriver(options);
            //输入指定的url地址
           //driver.get("http://www.baidu.com/");
            //控制浏览器窗口
            //driver.manage().window().
            //获取一个导航窗口
            navigation = driver.navigate();
            //加载到指定url
            navigation.to("http://www.baidu.com");
            //或者
            //driver.get("http://www.baidu.com");
    
            //id选择器获取指定元素,清空;需要看页面的自定义的id元素
            //driver.findElement(By.id("user_name")).clear();
            //模拟填用户名
       driver.findElement(By.id("user_name")).sendKeys("user");
            //id选择器获取指定元素,清空
            //driver.findElement(By.id("password")).clear();
            //模拟填密码
      driver.findElement(By.id("password")).sendKeys("pass");
            //模拟点击登录按钮
            driver.findElement(By.id("btn_login")).click();
    
            Thread.sleep(2000);
            WebElement page_container = driver.findElement(By.id("app_page_container"));
            //以此判断是否登录成功
            if (ObjectUtil.isNotNull(page_container)) {
                navigation.to("http://xxx");
                System.out.println("success");
            }
            //测试完成关闭浏览器
            //driver.close();
        }
    
        public static void test5(){
            System.setProperty("webdriver.chrome.driver","path");
            //创建WebDriver对象
            WebDriver driver = new ChromeDriver();
            //输入指定的url地址
    //        driver.get("http://www.baidu.com/");
            //获取一个导航窗口
            navigation = driver.navigate();
            //指定登陆页面
            String path = "http://xx";
            //加载到指定url
            navigation.to(path);
    
            try {
                /**
                 * 下面通过元素选择器对获取到的页面进行图片url抽取,通过url下载。
                 */
                List<WebElement> elements = driver.findElements(By.xpath("//div[@class='image-holder']/img"));
                for (WebElement element : elements) {
                    String src = element.getAttribute("src");
                    //DownLoadPicture.download(src);
                }
                driver.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    驱动访问问题

    本地测试验证基本没什么问题,但是docker打包发到服务器上后,无法运行。

    一开始想的是不是jar包的资源没访问到

    @Test
        public void tesPath () {
            String path1 = this.getClass().getResource("/driver/chromedriver").getPath();
            String path3 = service.class.getResource("/driver/chromedriver").getPath();
            String path2 = new ClassPathResource("driver/chromedriver").getPath();
            String path4 = this.getClass().getClassLoader().getResource("driver/chromedriver").getPath();
            String path5 = service.class.getClassLoader().getResource("driver/chromedriver").getPath();
            String path6 = getResourceFileByPath("/driver/chromedriver").getPath();
            String path7 = getResourceFileByPath("/driver/chromedriver").getAbsolutePath();
    String path8 = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            System.out.println(path1);
            System.out.println(path3);
            System.out.println(path2);
            System.out.println(path4);
            System.out.println(path5);
            System.out.println(path6);
            System.out.println(path7);
    
        }
    }
    //根据jar来拿文件路径,因为jar后不存在文件的自己的路径了
    public static File getResourceFileByPath(String path) {
            File file = null;
            final String resource = path;
            URL res = FileHelper.class.getResource(resource);
            if (res.getProtocol().equals("jar")) {
                try {
                    InputStream input = FileHelper.class.getResourceAsStream(resource);
                    file = File.createTempFile("tempfile", "");
                    OutputStream out = new FileOutputStream(file);
                    int read;
                    byte[] bytes = new byte[1024];
    
                    while ((read = input.read(bytes)) != -1) {
                        out.write(bytes, 0, read);
                    }
                    out.close();
                    file.deleteOnExit();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } else {
                //this will probably work in your IDE, but not from a JAR
                file = new File(res.getFile());
            }
    
            if (file != null && !file.exists()) {
                throw new RuntimeException("Error: File " + file + " not found!");
            }
    
            return file;
        }

    具体参照这里

    各种尝试拿文件方法,才想起来driver是个可执行文件... 

    拓展环境-手动

    容器镜像是ubuntu系统,大概分为两个步骤,第一下载谷歌浏览器,第二下载谷歌浏览器驱动

    下载谷歌浏览器

    如果没下载浏览器会报错,按报错信息来貌似没什么有效提示,查了才知道是缺少这个的原因

    unknown error: cannot find Chrome binary

    基本步骤:

    #拿到密钥
    wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
    #更换sourceList 
    sudo sh -c 'echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
    #更新apt
    sudo apt-get update
    #安装
    sudo apt-get install google-chrome-stable

    当然如果有被墙的话,可能要配下hosts或者更新系统基础镜像版本了。

    下载谷歌浏览器驱动

    得放到/usr/bin下

    #示例 可查看http://chromedriver.storage.googleapis.com/index.html
    wget --no-verbose -O /tmp/chromedriver_linux64.zip http://chromedriver.storage.googleapis.com/index.html?path=70.0.3538.16/chromedriver_linux64.zip 

    拓展环境-自动

    通过dockerfile实现配置接口,其实和手动添加类似。

    RUN apt-get update && 
        apt-get install -y gnupg wget curl unzip --no-install-recommends && 
        wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && 
        echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list && 
        apt-get update -y && 
        apt-get install -y google-chrome-stable && 
        CHROMEVER=$(google-chrome --product-version | grep -o "[^.]*.[^.]*.[^.]*") && 
        DRIVERVER=$(curl -s "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_$CHROMEVER") && 
        wget -q --continue -P /chromedriver "http://chromedriver.storage.googleapis.com/$DRIVERVER/chromedriver_linux64.zip" && 
        unzip /chromedriver/chromedriver* -d /chromedriver

    具体可参考下 github上两个配置文件:配置1配置2

    遇到的问题

    首次调用可以会碰到如下这个问题

    Chrome报错: error while loading shared libraries: libnss3.so libXss.so.1 libasound.so.

    需安装依赖,如果安装不了出现依赖404NOT FOUND,需要更新系统源文件source.List

    apt install libnss3-dev
    apt-get install libxss1
    apt-get install libasound2

    其次是路径问题,没访问到或者文件不对等

    Driver info: The driver is not  executable

     

    我始终记住:青春是美丽的东西,而且对我来说,它永远是鼓舞的源泉。——(现代)巴金
  • 相关阅读:
    从函数作用域和块级作用域看javascript的作用域链
    基于vue实现一个简单的MVVM框架(源码分析)
    发布-订阅模式
    希尔排序
    直接插入排序
    选择排序
    React Fiber源码分析 第三篇(异步状态)
    React Fiber源码分析 第二篇(同步模式)
    React Fiber源码分析 第一篇
    数据结构 之 树总结
  • 原文地址:https://www.cnblogs.com/flyinglion/p/15303927.html
Copyright © 2011-2022 走看看