首页 > 编程语言 >java selenium

java selenium

时间:2022-11-29 16:03:52浏览次数:66  
标签:java selenium driver import org openqa

selenium是一种web自动化测试的工具,可以控制浏览器,进行网页操作

准备

首先,下载谷歌驱动,下载地址
http://npm.taobao.org/mirrors/chromedriver/
查看自己的谷歌浏览器版本,选择与版本最近的下载。

示例

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
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.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * create by fzg
 * 2022/6/15 10:45
 */

@SpringBootTest
public class ServerWebTests {

    @Autowired
    private ChromeDriver driver;

    @Test
    public void getContent() throws IOException {
        System.setProperty("webdriver.chrome.driver", "D:/Program Files/chrome-driver/chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        driver = new ChromeDriver(chromeOptions);

        driver.get("https://so.gushiwen.cn/shiwenv_45c396367f59.aspx");

        System.out.println("fzg1===>" + driver.getTitle());

        String title = driver.findElement(By.xpath("//*[@id=\"sonsyuanwen\"]/div[1]/h1")).getText().toString();

        // 古诗的标题
        System.out.println("fzg===>" + driver.findElement(By.xpath("//*[@id=\"sonsyuanwen\"]/div[1]/h1")).getText());

        // 古诗内容
        WebElement cont = driver.findElement(By.id("contson45c396367f59"));
        System.out.println(cont.getText());
        String text = cont.getText();

        driver.close();

        String fileName = "C:\\Users\\Asus\\Desktop\\temp\\poetry.txt";
        Path path = Paths.get(fileName);

        try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
            writer.write(title);
        }
        try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
            writer.write("\n" + text);
        }

    }
}

利用selenium可以爬取网页元素

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;

/**
 * create by fzg
 * 2022/11/29 14:11
 */

@Slf4j
@SpringBootTest
public class SeleniumTest {

    @Autowired
    private ChromeDriver driver;

    @Test
    public void getImages(){
        System.setProperty("webdriver.chrome.driver", "D:/Program Files/chrome-driver/chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        driver = new ChromeDriver(chromeOptions);
        driver.get("https://picsum.photos/images");

        List<WebElement> elements = driver.findElements(By.className("download-url"));
        log.info("大小:" + elements.size());
        for (WebElement element : elements) {
            String imgUrl = element.getAttribute("href");
            downImage(imgUrl, UUID.randomUUID().toString());
        }
        driver.close();
    }

    public void downImage(String imageUrl,String fileName) {
        String file = "E:\\pictures\\java-repile-images";
        File files = new File(file);
        if (!files.exists()) {
            files.mkdirs();
        }

        InputStream is;
        FileOutputStream out;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            is = connection.getInputStream();
            // 创建文件
            File fileOfImg = new File(file + "/" + fileName + ".jpg");
            out = new FileOutputStream(fileOfImg);
            int i = 0;
            while ((i = is.read()) != -1) {
                out.write(i);
            }
            is.close();
            out.close();
            log.info(fileName + "下载成功");
        } catch (MalformedURLException e) {
            log.info("图片地址解析失败");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

标签:java,selenium,driver,import,org,openqa
From: https://www.cnblogs.com/Fantasyfzg/p/16935587.html

相关文章

  • JavaScript笔记
    JavaScript合集学完HTML5+CSS3的小伙伴,学习JS时,要多敲多练多想多拓展刚开始入门JS的时候,我们不需要纠结那么多,有些需要先记住,后面会慢慢明白为什么是这样的JS基础部分......
  • 【JAVA基础】String处理
    String处理字符串查找子串及截取//保存的头像文件的文件名Stringsuffix="";StringoriginalFilename=file.getOriginalFilename();......
  • 【JAVA基础】List处理
    List处理List使用Lists.partition()分片publicstatic<T>List<List<T>>partition(List<T>list,intsize)参数:该方法接受两个参数:list:该列表将根据分区大小分为......
  • Java的ExecutorService的shutdownNow()方法并不能保证一定会结束线程的解决办法
    这几天使用ExecutorService的时候遇到了在Task内部进行读取文件操作而导致死循环的问题,当我试图调用shutdownNow()方法的时候,发现并不是像我预想的一样会理解结束线程。我......
  • day07_java_数组
    d07Java数组(p51-p59)1.什么是数组?数组就是一组数的集合。数组是相同类型数据的有序集合。数组描述的是相同类型的若干个数据,按照一定的先后顺序排列组合而成。......
  • Java8新特性
    1.利用distinct去重 并保持数组的顺序ArrayList<Integer>list=newArrayList();list.add(7);list.add(5);list.add(9);list.a......
  • java如何高效地读取一个超大文件?(四种方式分析对比)
    读取大文件的四种方式本地压缩了一个文件夹,大概500M左右。虽然不是很大但是,相对还可以。方法1:Guava读取Stringpath="G:\\java书籍及工具.zip";Files.readLines(new......
  • java基础多线程之共享数据
    java基础巩固笔记5-多线程之共享数据线程范围内共享数据ThreadLocal类多线程访问共享数据几种方式本文主要总结线程共享数据的相关知识,主要......
  • Java 注解和反射(六)获取泛型,注解信息
    反射操作泛型**Java采用泛型擦出的机制来引入泛型,Java中的泛型仅仅是给编译器javac使用的,确保数据的安全性和免除强制类型转换问题,但是,一旦编译完成,所有和泛型有关的类......
  • JAVA面试题--Dubbo
    Dubbo1.Dubbo是什么?2.为什么要用Dubbo?3.Dubbo和Dubbox有什么区别?4.dubbo都支持什么协议,推荐用哪种?5.Dubbo需要Web容器吗?6.Dubbo内置了哪几种服务容器?7.Dubbo......