简体   繁体   English

Selenium WebDriver Java使用动态ID定位元素

[英]Selenium WebDriver Java locating an element with dynamic ID

I'm currently having troubles on locating this element with dynamic id. 我目前在使用动态ID定位此元素时遇到麻烦。 Here are the screenshots below. 这是下面的截图。

在此处输入图片说明

在此处输入图片说明

What i have right now is the element of Variables (8) //a[contains(.,'Variables (8)')]. 我现在拥有的是变量(8)//a[contains(.,'Variables(8)')]的元素。 What i need is only the "Variables" since the number 8 is always changing. 我需要的只是“变量”,因为数字8总是在变化。

Any thoughts on this? 有什么想法吗? Any ideas will be much appreciated. 任何想法将不胜感激。 Thanks 谢谢

First of all 'Variables (8)' is not Id, its text. 首先,“变量(8)”不是Id,而是其文本。 Id's are not dynamic since they represent unique identifier for the web element. ID不是动态的,因为它们代表Web元素的唯一标识符。 This will look like this (based on your example): 如下所示(根据您的示例):

<div class="field" id="fieldId">

As for your question, you can find the element by partial linked text: 至于您的问题,您可以通过部分链接的文本找到该元素:

driver.findElement(By.partialLinkText("Variables"));

This will give you the a element no meter what the number is. 这将为您提供a没有计量器的数字。

What I understand from your question is you want to locate the <a> tag which contains text "Variables". 我从您的问题中了解到的是,您想找到包含文本“变量”的<a>标记。 Try using this xpath: 尝试使用此xpath:

//div[@class="field"]/a[contains(.,"Variables")]

This xpath will locate the <a> tag after the div tag with class name =field and Contains method with <a> tag will find the element which contains text "Variables" 该xpath将在具有类名称= field的div标记之后找到<a>标记,并且具有<a>标记的Contains方法将找到包含文本“ Variables”的元素

You can try the below: 您可以尝试以下方法:

driver.findElement(By.cssSelector("a:contains('Variables')")); driver.findElement(By.cssSelector( “A:含有( '变量')”));

If you want the word "Variables" , use the below: 如果您想使用“变量”一词,请使用以下命令:

String str = driver.findElement(By.cssSelector("a:contains('Variables')")).getText().split(" ")[0]; 字符串str = driver.findElement(By.cssSelector(“ a:contains('Variables')”))。getText()。split(“”)[0];

Hope this Helps.... 希望这可以帮助....

尝试这个:

 String varText =    driver.findElement(By.cssSelector("div.triggerFirst>div:nth-child(1)>a")).getText();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM