Webdriver API的使用(带例子)

37 阅读9分钟

元素定位

我们看看webdriver给了几种元素定位方法

1. By.CssSelector

cssSelector 是基于 CSS 选择器语法进行定位的,它允许你使用 CSS 选择器来精确定位元素。CSS 选择器的语法非常强大,可以通过标签名、类名、ID、属性以及它们的组合来定位元素。以下是一些常用的 CSS 选择器示例:

1.1. 基本选择器

  1. 通过标签名定位元素:
WebElement element = webDriver.findElement(By.cssSelector("input"));
  1. 通过类名定位元素:
WebElement element = webDriver.findElement(By.cssSelector(".className"));
  1. 通过ID定位元素:
WebElement element = webDriver.findElement(By.cssSelector("#id"));
  1. 通过属性定位元素:
WebElement element = webDriver.findElement(By.cssSelector("[name='elementName']"));

1.2. 组合选择器

  1. 通过标签名和类名组合定位元素:
WebElement element = webDriver.findElement(By.cssSelector("input.className"));
  1. 通过标签名和ID组合定位元素:
WebElement element = webDriver.findElement(By.cssSelector("input#id"));
  1. 通过多个类名组合定位元素:
WebElement element = webDriver.findElement(By.cssSelector(".class1.class2"));

2. By.ClassName

WebElement element = webDriver.findElement(By.className("className"));

3. By.Xpath

XPath(XML Path Language)是一种用于在XML文档中查找信息的语言,它有两种定位元素的方法。

3.1. 定位方法

  1. 绝对路径:
  • 从根节点开始,路径以 / 开头。
/html/body/div
  1. 相对路径
  • 从当前节点开始,路径以 // 开头。
//div

3.2. 具体示例

  1. 定位所有
    元素:
//div
  1. 定位带有特定属性的元素:
  • 具有 class="example" 的所有元素:
//*[@class='example']
  1. 定位特定属性值的元素:
  • 具有 id="content" 的元素:
//*[@id='content']
  1. 层级定位:
  • 定位某个
    内的
//div/span
  1. 索引定位:
  • 定位第一个
    元素:
(//div)[1]
  1. 复合条件定位:
  • 具有 class="example" 并且 id="content" 的元素:
//*[@class='example' and @id='content']
  1. 文本内容定位:
  • 包含特定文本的元素:
//*[contains(text(),'Example Text')]

4. By.TagName

//定位所有名为“tagName”的标签
List<WebElement> allLinks = webDriver.findElements(By.tagName("tagName"));//tagName为标签名,例如a标签

5. By.Name

WebElementsearchBox= webDriver.findElement(By.name("name"));  

6. By.PartialLinkText

有的时候定位的为部分文字链接,可以使用 By.partialLinkText

WebElement aboutLink = webDriver.findElement(By.partialLinkText("文字链接"));//例如hao123只需要输入部分文字:hao、123等

7. By.LinkText

linkText搜索的是完整的文本链接

WebElement newsLink = webDriver.findElement(By.linkText("完整文本链接"));//例如hao123

8. By.Id

WebElement element = webDriver.findElement(By.id("id"));

9. 使用baidu举例

9.1. 使用百度搜索稀土掘金,分为两个步骤,先是在输入框中输入“稀土掘金”再点击搜索按钮“百度一下”。

  1. 定位搜索栏:

代码

WebElement searchBox = webDriver.findElement(By.cssSelector(".s_ipt"));
//设置搜索值
searchBox.sendKeys("稀土掘金");
WebElement searchBox = webDriver.findElement(By.id("kw"));
//设置搜索值
searchBox.sendKeys("稀土掘金");
WebElement searchBox = webDriver.findElement(By.name("wd"));
//设置搜索值
searchBox.sendKeys("稀土掘金");
WebElement searchBox = webDriver.findElement(By.className("s_ipt"));
//设置搜索值
searchBox.sendKeys("稀土掘金");
  1. 定位搜索按钮

WebElement searchBox = webDriver.findElement(By.id("su"));
//点击按钮
search.click();

代码和上面差不多,就不一一举例了。

  1. 整体代码
public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
//    WebElement searchBox = webDriver.findElement(By.cssSelector(".s_ipt"));
//    WebElement searchBox = webDriver.findElement(By.id("kw"));
// 	  WebElement searchBox = webDriver.findElement(By.name("wd"));
    WebElement searchBox = webDriver.findElement(By.className("s_ipt"));
    searchBox.sendKeys("稀土掘金");
    WebElement search = webDriver.findElement(By.className("s_btn"));
    search.click();
}

运行结果

9.2. partialLinkText、linkText举例

定位一下百度首页的hao123

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    //文本链接的部分文字,“hao123”可以写为“hao”、“123”、“o12”等
    WebElement newsLink = webDriver.findElement(By.partialLinkText("hao"));
    newsLink.click();
}

运行结果

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    //文本链接所有文字
    WebElement newsLink = webDriver.findElement(By.linkText("hao123"));
    newsLink.click();
}

运行结果

9.3. Xpath举例

不会写路径怎么办?

首先定位到搜索框,然后右击整行代码,选择copy,他会给出两个路径,第一个是相对路径,第二个是绝对路径

相对路径://*[@id="kw"]
绝对路径:/html/body/div[1]/div[1]/div[5]/div/div/form/span[1]/input
public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    WebElement search = webDriver.findElement(By.xpath("//*[@id="kw"]"));
    search.sendKeys("稀土掘金");
}

运行结果

操作测试对象

定位元素是第一步,定位完成需要对元素进行操作。比如上面举例中的click就是其中一种。

webdriver 中比较常用的操作对象的方法有下面几个:

  • click 点击对象
  • send_keys 在对象上模拟按键输入
  • clear 清除对象输入的文本内容
  • submit 提交
  • text 用于获取元素的文本信息

示例

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");

    // 1. 使用send_keys在搜索框中输入内容
    WebElement searchBox = webDriver.findElement(By.id("kw"));
    searchBox.sendKeys("稀土掘金");

    // 2. 使用click点击搜索按钮
    WebElement searchButton = webDriver.findElement(By.id("su"));
    searchButton.click();

    // 等待页面加载结果
    try {
        Thread.sleep(2000); // 简单等待2秒,可用显式等待替代
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // 3. 获取搜索结果的文本信息
    //相对路径直接通过上面教程获取就行(随便搜一个东西然后F12打开按照步骤获取)
    WebElement firstResult = webDriver.findElement(By.xpath("//div[@id='content_left']//h3/a"));
    String resultText = firstResult.getText();
    System.out.println("First search result: " + resultText);

    // 4. 清除搜索框中的内容
    searchBox.clear();

    // 5. 再次输入内容并提交表单
    searchBox.sendKeys("WebDriver 示例");
    searchBox.submit();

    // 等待页面加载结果
    try {
        Thread.sleep(2000); // 简单等待2秒,可用显式等待替代
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // 关闭浏览器
    webDriver.quit();
}

运行结果

添加等待

等待是非常重要,它能确保页面加载完毕并且元素可见或可点击。以下是几种等待方式:

  1. 隐式等待(Implicit Wait) :在 WebDriver 实例上设置一次,之后所有的查找操作都会等待指定的时间。
  2. 显式等待(Explicit Wait) :针对特定元素设置的等待条件,在满足条件之前一直等待。
  3. 休眠(Thread.sleep) :强制让线程休眠指定的时间,不推荐用于实际项目,因为它会导致不必要的等待时间。

1. 隐式等待

隐式等待是在 WebDriver 实例上设置的全局等待时间。WebDriver 会在查找每个元素时等待指定的时间,直到元素出现。

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    // 设置隐式等待时间为10秒
    webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    webDriver.get("https://www.baidu.com");
    WebElement search = webDriver.findElement(By.xpath("//*[@id="kw"]"));
    search.sendKeys("稀土掘金");
}

2. 显式等待

显式等待是针对特定条件设置的等待时间。它在指定的时间内每隔一段时间检查一次条件,直到条件满足或超时。

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    WebDriverWait webDriverWait = new WebDriverWait(webDriver,10);

    webDriver.get("https://www.baidu.com");
    WebElement search = webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id="kw"]")));
    search.sendKeys("稀土掘金");
}
  • WebDriverWait: WebDriverWait 是 Selenium 提供的一个类,用于实现显式等待。它会等待指定的条件满足直到超时。
WebDriverWait wait = new WebDriverWait(driver, 10);

这行代码创建了一个 WebDriverWait 对象,设置了最长等待时间为 10 秒。

  • ExpectedConditions: ExpectedConditions 是一个辅助类,提供了许多常用的条件(例如,元素是否可见、元素是否可点击等)。
  • visibilityOfElementLocated: visibilityOfElementLocated 是 ExpectedConditions 中的一个静态方法,它等待特定的元素在页面上变得可见。该方法接受一个定位器作为参数。
  • By.id("kw") : 这是一个定位器,通过元素的 id 属性来查找元素。在这个例子中,它查找 id 为 kw 的元素。
  • wait.until(...) : wait.until 方法会等待,直到所提供的条件为真,或者超时。在这种情况下,它会等待元素 id 为 kw 的元素变得可见。

3. 休眠

休眠会让线程强制等待指定的时间。这种方式不推荐用于实际项目,因为它会导致不必要的等待时间。 这个代码我们经常在多线程中会看到,此处就做一个简单介绍。

try {
    // 强制休眠2秒
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

打印信息

这个在上面举过例子了,直接看代码吧,很简单

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");

    // 1. 使用send_keys在搜索框中输入内容
    WebElement searchBox = webDriver.findElement(By.id("kw"));
    searchBox.sendKeys("稀土掘金");

    // 2. 使用click点击搜索按钮
    WebElement searchButton = webDriver.findElement(By.id("su"));
    searchButton.click();
    // 等待页面加载结果
    try {
        Thread.sleep(2000); // 简单等待2秒,可用显式等待替代
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // 3. 打印搜索结果的第一条文本信息
    WebElement firstResult = webDriver.findElement(By.xpath("//div[@id='content_left']//h3/a"));
    String resultText = firstResult.getText();
    System.out.println("First search result: " + resultText);

}

控制浏览器

1. 浏览器最大化

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    //页面最大化
    webDriver.manage().window().maximize();
}

2. 设置窗口大小

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    //页面最大化
    webDriver.manage().window().setSize(new Dimension(800, 600));
}

3. 后退、前进操作

public static void main(String[] args) throws InterruptedException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    Thread.sleep(1000);
    //搜索稀土掘金
    webDriver.get("https://www.google.com");
    Thread.sleep(1000);
    //返回操作
    webDriver.navigate().back();
    //前进操作
    Thread.sleep(1000);
    webDriver.navigate().forward();
}

4. 控制滚动条

public static void main(String[] args) {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    WebElement searchBox = webDriver.findElement(By.id("kw"));
    searchBox.sendKeys("稀土掘金");

    WebElement searchButton = webDriver.findElement(By.id("su"));
    searchButton.click();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    JavascriptExecutor js = (JavascriptExecutor) webDriver;
    //滚动到底部
    js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //滚动到顶部
    js.executeScript("window.scrollTo(0, 0);");

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //滚动到指定位置
    js.executeScript("window.scrollTo(0, 500);");
}

键盘组合键

可以使用 Actions 类来执行键盘事件和组合键。

public static void main(String[] args) throws InterruptedException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    WebElement searchBox = webDriver.findElement(By.id("kw"));
    searchBox.sendKeys("稀土掘金");
    WebElement searchButton = webDriver.findElement(By.id("su"));
    searchButton.click();


    Actions actions = new Actions(webDriver);
    //按下shift输入文字(按住shift = 大写)
    actions.keyDown(Keys.SHIFT).sendKeys(searchBox, "selenium webdriver").keyUp(Keys.SHIFT).perform();
    actions.sendKeys(Keys.ENTER).perform();
}

鼠标事件

单击、双击

双击没想到好的举例方法,使用方法是相同的,这里就不演示了

public static void main(String[] args) throws InterruptedException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    WebElement searchBox = webDriver.findElement(By.id("kw"));
    searchBox.sendKeys("稀土掘金");
    WebElement searchButton = webDriver.findElement(By.id("su"));


    Actions actions = new Actions(webDriver);
    actions.click(searchButton).perform();  // 单击
    //actions.doubleClick(searchButton).perform();  // 双击
}

拖动

public static void main(String[] args) throws InterruptedException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    WebDriverWait wait = new WebDriverWait(webDriver, 10);
    WebElement searchBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("kw")));
    searchBox.sendKeys("稀土掘金");

    WebElement searchButton = webDriver.findElement(By.id("su"));
    searchButton.click();

    // 等待搜索结果加载,从第1条查询数据跳到第8条
    WebElement source = wait.until(ExpectedConditions.
            visibilityOfElementLocated(By.xpath("//*[@id="1"]/div/div[1]/h3")));
    WebElement target = wait.until(ExpectedConditions.
            visibilityOfElementLocated(By.xpath("//*[@id="8"]/div/div[1]/h3/a")));


    Actions actions = new Actions(webDriver);
    actions.moveToElement(source).clickAndHold().moveToElement(target).release().perform();

}

定位一组元素

public static void main(String[] args) throws InterruptedException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--remote-allow-origins=*");
    WebDriver webDriver = new ChromeDriver(options);
    webDriver.get("https://www.baidu.com");
    WebDriverWait wait = new WebDriverWait(webDriver, 10);
    WebElement searchBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("kw")));
    searchBox.sendKeys("稀土掘金");

    WebElement searchButton = webDriver.findElement(By.id("su"));
    searchButton.click();

    // 等待搜索结果页面加载
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("content_left")));

    List<WebElement> source = webDriver.findElements(By.tagName("a"));
    for (WebElement element : source) {
        System.out.println(element.getText());
    }
}

上传文件

上传文件没有找具体例子

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.get("https://example.com");

    WebElement uploadElement = driver.findElement(By.id("uploadElementId"));
    uploadElement.sendKeys("path/to/file.txt");

    driver.quit();
}