java - 如何在 selenium java 中捕获和导航 <a> 和 <span> 标签下的元素

标签 java selenium selenium-webdriver selenium-ide selenium-rc

我想捕获元素并在链接到 <a> 下的该元素的页面上导航标签和<span>标签。我尝试使用 selenium IDE,但它无法捕获这些元素。所以我用java编写了代码,并引用了stackoverflow的许多链接,但我仍然无法解决我的问题。 下面是我的java代码:

package com.selenium;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirstTestSelenium {

    public static void main(String[] args) {
        // declaration and instantiation of objects/variables
        WebDriver driver;

        System.setProperty("webdriver.firefox.marionette", "D:\\geckodriver.exe");
        driver = new FirefoxDriver();
        Session session;
        String baseUrl = "";
        String expectedTitle = "QlikView";
        String actualTitle = "";
        // launch Fire fox and direct it to the Base URL
        driver.get(baseUrl);
        actualTitle = driver.getTitle();
        System.out.println(actualTitle);
        if (actualTitle.contentEquals(expectedTitle)) {
            System.out.println("Test Passed!");
        } else {
            System.out.println("Test Failed");
        }
        // driver.findElement(By.xpath("//span[text()='Demand
        // Summary']")).getText();
        // close Fire fox
        driver.findElement(By.xpath("//*[normalize-space()='S/D Summary']"));
        ;

        driver.close();

        // exit the program explicitly
        System.exit(0);
    }

}

下面是我的用户界面代码:

<li style="display: list-item;" order="2" rel="DocumentSH07" id="Document\SH07">
    <a style="color: rgb(0, 0, 0); background: rgb(255, 255, 255) none repeat scroll 0% 0%;" href="javascript:;">
    <span style="font-weight: normal; font-family: Arial; font-size: 9pt; font-style: normal; text-decoration: none;">Demand Summary</span>
    </a>
    </li>

请帮助我解决我的问题,因为我是 Selenium 新手,但已尽力。它给出了 NoSuchElementFound 异常。
谢谢!

最佳答案

您的定位器正在寻找“需求摘要”

"//*[normalize-space()='Demand Summary']"

但是您提供的 HTML 显示“S/​​D 摘要”

<span ...>S/D Summary</span>

将定位器更改为“//*[.='S/D Summary']”,它应该可以工作。

关于java - 如何在 selenium java 中捕获和导航 <a> 和 <span> 标签下的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030664/

相关文章:

javascript - 在 Webdriver JS 测试期间无法切换窗口

java - 支柱2 : textbox label is not displayed

java - 使用较小的 JRE 打包

java - 如何使用 Java 中的函数和方法循环读取字符串

python - Selenium Python 绕过 "Open <...>.app?"

selenium - 检查元素是否确实对用户可见

selenium-webdriver - WebDriverException ... moveto 与已知命令不匹配

java - 如何检查Java Eclipse 插件开发中的IFile 是否真的存在?

python : no module named selenium

java - Selenium(Java)、java.lang.AssertionError