官方文档:https://www.selenium.dev/documentation
chromedriver下载地址:注意:需要下载与浏览器匹配版本的
http://chromedriver.storage.googleapis.com/index.html
http://npm.taobao.org/mirrors/chromedriver/
代码示例:
    public static void main(String[] args) throws InterruptedException {
//获取项目路径
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
// 设置系统标识,因为 chromedriver.exe 存放在 resources\plugins\目录下
System.setProperty("webdrive.chrom.drive", path+"plugins\\chromedriver.exe");
//获取Chrome 浏览器的驱动
WebDriver driver = new ChromeDriver();
//        打开一个网址
driver.get("https://wwww.baidu.com");
//        八种获取元素的方法id,name,className,tagName,linkText,partialLinkText,cssSelector,xpath
WebElement element;
//        ********************【ID 选择器1】********************************
element = driver.findElement(By.id("kw"));   // 根据属性Id获取 百度搜索框
element.sendKeys("selenium"); // 搜索框中填充搜索内容
//        ********************【Name 选择器2】******************************
driver.findElement(By.name("wd")).sendKeys("3355");  //根据属性name获取
//        ********************【className 选择器3】*************************
//根据属性className获取【百度一下】按钮,class之间不能有空格,但可以只用部分class
element = driver.findElement(By.className("s_btn"));
element.submit();
//        ********************【linkText 选择器4】****************************
element = driver.findElement(By.linkText(""));  //根据linkText获取
System.out.println(element.getText());
//        ********************【partialLinkText 选择器5】**********************
element = driver.findElement(By.partialLinkText(""));  // 根据部分linkText获取
System.out.println(element.getText());
//        ********************【cssSelector 选择器6】***************************
element = driver.findElement(By.cssSelector("")); //根据css选择器获取
System.out.println(element.getText());
//        ********************【xpath 选择器7】*********************************
element = driver.findElement(By.xpath(""));   // 根据xpath 获取
System.out.println(element.getText());
//        ********************【tagName 选择器8】*******************************
element = driver.findElement(By.tagName("")); // 根据tagName获取
System.out.println(element.getText());
//        driver.findElement(By.id("su")).submit();//提交搜索【百度一下】按钮的id 为 su
Thread.sleep(5*1000);//为了看效果,5秒中后关闭
// close 只是关闭窗口,quit 关闭窗口并关闭进程
//        driver.close();
driver.quit();
}
Selenium 提供了练级打怪的场:https://bonigarcia.dev/selenium-webdriver-java/index.html
赶紧开始自己的野蛮发育吧

【啰嗦一下】:

现在浏览器多数会自动更新,就会出现之前还运行正常的代码,后期提示版本不支持的情况;
这种情况 Selenium 也提供了支持:
WebDriverManager是一个开源的Java库,它以完全自动化的方式对Selenium WebDriver所需的驱动程序进行下载、设置和维护
官方秘籍:https://bonigarcia.dev/webdrivermanager/
类 API:https://www.selenium.dev/selenium/docs/api/java/index.html?overview-summary.html
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。