查找特定属性,Selenium Xpath Java

Finding a specific attribute, Selenium Xpath Java

我有以下代码,我试图从 (data-id) 中提取特定属性。 我刚开始使用 selenium,现在已经为此痛苦了一天多。

为了添加上下文,我将向您介绍我正在努力实现的目标的一些背景知识。

我有一个有拍卖的网页,拍卖有一个 ID,拍卖中的所有项目都有唯一的 ID,但都 link 到原始拍卖 ID。 我正在尝试提取元素的 "data-id" 属性,但是我还没有找到方法。 这是我试图从中获取 ID 的代码片段。

<div class="dropdown open">
  <a class="dropdown-toggle form-control" href="#" data-toggle="dropdown">
  <ul class="dropdown-menu dropdown-menu-form" role="menu">
    <li id="liAuction4c42556772376a443736343d">
      <label class="checkbox">
        <input id="chkAuction4c42556772376a443736343d" class="auction" type="checkbox" data-caption="09-10-2015 10:30:00" data-id="4c42556772376a443736343d" checked="checked"/>
09-10-2015 10:30:00
      </label>
    </li>
  </ul>
</div>

我去过很多论坛并搜索了整个 google 并没有找到适合我的解决方案,否则我不会发布问题并且看起来像一个完整的菜鸟。

我曾尝试使用 .getAttribute,但我遇到了一些问题,代码从未编译过,我想我做错了什么。

String dataID = selenium.findElement(By.xpath("//*[starts-with(@id, 'liAuction')]")).getAttribute("data-id");

当我尝试上述操作时,"findElement" 部分带有红色下划线并且我收到以下消息,

"The method findElement(By) is undefined for the type Selenium".

如果我把周围的父母改成这样;

String dataID = selenium.findElement(By.xpath("//*[starts-with(@id, 'liAuction')]").getAttribute("data-id"));

"findElement" 不再带有下划线,但是现在“.getAttribute”部分带有红色下划线,我收到以下消息,"The method getAttribute(String) is undefined for the type By"

在我即将把我的笔记本电脑从 window 中扔掉时,我真的很感激能得到一些帮助,我真的不想丢失我的所有文件。

提前致谢

托尼

使用下面的 xpath:-

//input[@id='chkAuction4c42556772376a443736343d']/@data-id

然后使用:-

String dataID = selenium.findElement(By.xpath("//input[@id='chkAuction4c42556772376a443736343d']/@data-id")).gettext();

完整代码:-

static WebDriver driver=null;
    public static void main(String[] args) {
         driver = new FirefoxDriver();
         driver.get("URL");
         String dataID = driver.findElement(By.xpath("//input[@id='chkAuction4c42556772376a443736343d']/@data-id")).gettext();
         System.out.println(dataID);
}

希望对您有所帮助:)

您可以使用getAttribute方法。

首先找到输入元素,然后提取data-id:

WebElement inputElement = selenium.findElement(By.id("chkAuction4c42556772376a443736343d"));
String data-id = inputElement.getAttribute("data-id");

您好,我建议您使用以下代码。绝对没问题。

WebElement element = selenium.findElement(By.xpath("//input[@class='auction']"));
String dataId= element..getAttribute("data-id");

详情

我正在使用以下 xpath //input[@class='auction'] 识别对象并将其保存到 WebElement 变量。

然后通过使用 getAttribute() 我从 data-id

获取字符串

感谢您与这些人的交流,没想到这么快就得到了答复。

我需要使用以下行来检索元素的 "data-id" 属性。

String dataID = selenium.getValue("//input[@id='chkAuction4c42556772376a443736343d']/@data-id");

这最终比最初想象的要容易得多,我要感谢@Shubham Jain 的帮助,他的建议让我找到了我需要去的地方。

我希望这对以后的其他人有所帮助