5

我正在研究 Selenium 框架 2.0 Web 驱动程序,我想从具有数据自动化 ID 等属性的跨度中获取价值。HTML代码如下

<span data-automation-id="SEL_ERR">
  Error Description
</span>

现在我想阅读具有属性data-automation-id设置为 SEL_ERR 的跨度文本。

有人可以帮助我修复代码吗,因为我已经尝试过下面的代码但徒劳无功。

driver.findElement(By.tagName("span")).getAttribute("data-automation-id");
4

2 回答 2

6

这很简单,真的。您目前正在获得整个文档中的 一个。 span

你怎么知道那是不是你想要的?

见面,.findElements()。它不会获取满足定位器的第一个元素,而是会为您提供满足条件的每个元素的列表。

您没有共享太多 HTML,所以我不知道这是否是一个独特的元素。

但是,您有两种方法:

1).findElements用于获取所有元素,然后将span其过滤到特定具有data-automation-id值为的属性的元素SEL_ERR

或(推荐):

2) 使用.findElement专门针对 1) 中讨论的元素的选择器...如果 Selenium 找不到它,使用更有针对性的选择器,那么您知道它不存在。

driver.findElement(By.cssSelector("span[data-automation-id='SEL-ERR']"));

或者:

3) 对 2) 的修改。如果 Selenium 找不到它,它会抛出异常。例外是昂贵的。您可以.findElements改用(在 1 中提到),如果找不到您要查找的元素,它将简单地返回一个空列表:

driver.findElements(By.cssSelector("span[data-automation-id='SEL-ERR']")).size() != 0;
于 2013-11-08T15:05:05.097 回答
0

我正在使用 selenium、jquery 和 javascript 的元素。

我有不同的属性属于没有 ID 或名称的 botton,只有 data-automation-id,如下例所示:

<button type="button" 
        data-automationid="FieldRenderer-name" 
        data-selection-invoke="true" 
        class="ms-Link nameField_f59ebb65 clickable_f59ebb65 root-203" 
        title="BD Operacion">BD Operacion</button>

数据仓库

如您所见,重复了名称 data-automationid

我怎样才能访问该元素?

这不起作用,是我最接近的

driver.FindElement(By.CssSelector("//button[@data-automation-id='FieldRenderer-name'])[1]")).Click();
于 2019-10-25T18:50:33.657 回答