Selenium Java WebDriverAPI 接口操作4

一、API操作代码实例

1.1 访问网址

@Test
public void visitURL() {
    String baseUrl = "http://www.sogou.com";
    driver.get(baseUrl);
    // 或者
    driver.navigate().to(baseUrl);
}

1.2 返回上/下一页,刷新

@Test
public void visitURL() {
    String url1 = "http://www.sogou.com";
    String url2 = "http://www.baidu.com";
    driver.navigate().to(url1);
    driver.navigate().to(url2);
    // 返回上一页
    driver.navigate().back();
    // 前进下一页
    driver.navigate().forward();
    // 刷新
    driver.navigate.refresh();
}

1.3 操作浏览器窗口

@Test
public void operateBrowser() {
    Point point = new Point(150, 150);
    Dimension dimension = new Dimension(500, 500);
    // 设定浏览器在屏幕上的位置
    driver.manage().window().setPosition(point);
    // 设定浏览器窗口大小
    driver.manage().window().setSize(dimension);
    // 获取浏览器在屏幕的位置
    System.out.println(driver.manage().window().getPosition());
    // 获取窗口的大小
    System.out.println(driver.manage().window().getSize());
    // 窗口最大化
    driver.manage().window().maximize();
}

1.4 获取页面title属性/源代码/URL

@Test
public void testweb() {
    driver.get("http://www.sogou.om");
    // 获取页面的title属性
    String title = driver.getTitle();

    // 获取页面源代码
    String pageSource = driver.getPageSource();
    // 断言页面源代码包含“购物”关键字
    Assert.assertTrue(pageSource.contains("购物"));

    // 获取当前页面的URL
    String currentPageUrl = driver.getCurrentUrl();
}

1.5 清除文本框,再输入内容

@Test
public void testweb() {
    WebElement input = driver.findElement(By.id("test"));
    // 清除文本框
    input.clear();

    // 输入指定内容
    String text = "测试内容";
    input.sendKeys(text);
}

1.6 单击按钮/双击元素

@Test
public void testweb() {
    WebElement button = driver.findElement(By.id("button"));
    // 单击按钮
    button.click();
    
    // 双击元素
    WebElement inputBox = driver.findElement(By.id("inputBox"));
    Actions builder = new Actions(driver);
    builder.doubleClick(inputBox).build().perform();
}

1.7 操作单选下拉列表

@Test
public void testweb() {
    Select dropList = new Select(driver.findElement(By.name("fruit"));
    // 断言下拉列表不支持多选
    Assert.assertFalse(dropList.isMultiple());

    // 断言当前选中文本
    Assert.assertEquals("桃子", dropList.getFirstSelectedOption().getText());

    // 选中第四项
    dropList.selectByIndex(3);

    // 通过value值进行选中操作
    dropList.selectByValue("山楂");

    // 通过选项文字进行选中操作
    dropList.selectByVisibleText("荔枝");
}

1.8 操作多选选择列表

@Test
public void testweb() {
    Select dropList = new Select(driver.findElement(By.name("fruit"));
    // 断言支持多选
    Assert.assertTrue(dropList.isMultiple());

    // 可通过索引、value、visibleText进行选中操作,与单选相同
    // 取消所有选中状态
    dropList.deselectAll();

    // 取消操作与选中操作相似,只是在方法前面加上de
    // 通过索引取消选中第四项
    dropList.deselectByIndex(3);
}

1.9 执行js

package cn.amnotgcs;

import org.testng.annotations.Test;
import org.testng.reporters.Files;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;

import java.io.File;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;


public class NewTest {
	
  @Test
  public void f() {
	  WebDriver driver = new EdgeDriver();
	  driver.get("http://www.sogou.com");
	  
	  JavascriptExecutor js = (JavascriptExecutor) driver;
	  String title = (String) js.executeScript("return document.title");
	  Assert.assertTrue(title.contains("搜狗"));
	  
	  String searchButtonText = (String) js.executeScript("var button = document.getElementById('stb');return button.value");
	  System.out.println(searchButtonText);
	  
	  driver.quit();
  }
 
  @BeforeMethod
  public void BeforeMethod() {
	  
  }
}

1.10 模拟鼠标键盘操作

@Test
public void testweb() {
    driver.get("http://www.sogou.com");
    Actions action = new Actions(driver);

    // 模拟键盘操作
    action.keyDown(Keys.CONTROL);
    action.keyDown(Keys.SHIFT);
    action.keyUp(Keys.CONTROL);            
    actoin.keyDown(Keys.SHIFT).sendKeys("abcdef").perform();

    // 模拟鼠标右键
    action.contextClick(driver.findElement(By.id("query"))).perform();

    // 鼠标悬浮
    WelElement link1 = driver.findElement(By.id("linkaaa");
    action.moveToElement(link1).perform();

    // 鼠标按住不动
    action.clickAndHold(link1).perform();
    // 释放鼠标
    action.release(link1).perform();
}

1.11 获取元素属性

// 获取元素的value属性
<元素>.getAttribute("value");

// 获取元素css的width属性
<元素>.getCssValue("width");

1.12 等待

// 隐式等待
// 没有立刻找到元素时,会每隔一段时间重新查找,超过最长等待时间则报错
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// 显式等待
// 显式等待更节约时间,推荐使用
// 设置最长等待时间
WebDriverWait wait = new WebDriverWait(driver, 10);
// 判断p标签是否在页面中
wait.until(ExpectedConditions.presenceOFElementLocated(By.xpath("//p")));
// 判断对象中是否包含某些关键字
wait.until(ExpectedConditions.textToBePresentInElement(p, "某些关键字"));

// 自定义的显式等待
@Test
public void testweb() {
    try{
        // 判断food元素是否包含“爱吃”关键字
        Boolean containTextFlag = (new WebDriverWait(driver, 10))
            .until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                  return d.findElement(By.id("food")).getText().contains("爱吃");
            }
      });
    } catch(NoSuchElementException e) {
        Assert.fail("没找到");
    }
}

其他显示等待方法:

等待条件 WebDriver方法
元素是否可用或可被单击 elementToBeClickAble(By locator)
元素处于选中状态 elementToBeSelected(WebElement element)
元素存在 presenceOfElementLocated(By locator)
元素包含某些文字 textToBePresentInElement(By locator)
元素页面值 textToBePresentInElementValue(Bylocator String)
标题 titleContains(String title)

二、新窗口及弹窗处理

2.1 使用标题识别新窗口

2.2 使用页面文字识别新窗口

2.3 操作JavaScript的Alert/confirm/prompt弹窗

// 确认alert框
Alert alert = driver.switchTo().alert();
Assert.assertEquals("这是弹窗的内容", alert,getText());
alert.accept();

// 操作confirm框
Alert alert = driver.switchTo().alert();
Assert.assertEquals("这是confirm框", alert.getText());
// 确认
alert.accept();
// 拒绝
alert.dismiss();

// 操作confirm框
Alert alert = driver.switchTo().alert();
Assert.assertEquals("这是prompt框", alert.getText());
alert.sendKeys("这是输入内容")
// 接受
alert.accept();
// 拒绝
alert.dismiss();

2.4 操作frame

// 切换到frame
driver.switchTo().frame("<frameName>")

// 如果想切换到其它frame,需要先回到默认文档流
driver.switchTo().defaultContent();

// 使用索引进入指定frame,索引从0开始
driver.switchTo().frame(1);

// 遍历 frame
// 当有多个frame时,可以找到页面上所有frame,存储到容器中,然后遍历
List<WebElement> frames = driver.findElements(By.tagName("frame"));
for (WebElement frame:frames) {
    driver.switchTo().frame(frame);
    if (xxxx) {
          // Assert....
          break;
    } else {
          driver.switchTo().defaultContent();
    }
}

2.5 操作cookies

@Test
public void testCookie() throws Exception {
	  driver.get("http://www.sogou.com");
	  Set<Cookie> cookies = driver.manage().getCookies();
	  Cookie newCookie = new Cookie("cookieName", "cookieValue");
	  System.out.println(String.format("Domain->name->value->expiry->path"));
	  for(Cookie cookie:cookies) {
		  System.out.println(
				  String.format("%s->%s->%s->%s->%s",
						  cookie.getDomain(),
						  cookie.getName(),
						  cookie.getValue(),
						  cookie.getExpiry(),
						  cookie.getPath()));
	  }
  }

运行结果:

// 通过名字删除cookie
driver.manage().deleteCookieNamed("CookieName");
	  
// 通过对象删除cookie
driver.manage().deleteCookie(newCookie);
	  
// 删除所有cookie
driver.manage().deleteAllCookies();
posted @   那个白熊  阅读(446)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示