简体   繁体   中英

Selenium WebDriver Java locating an element with dynamic ID

I'm currently having troubles on locating this element with dynamic id. Here are the screenshots below.

在此处输入图片说明

在此处输入图片说明

What i have right now is the element of Variables (8) //a[contains(.,'Variables (8)')]. What i need is only the "Variables" since the number 8 is always changing.

Any thoughts on this? Any ideas will be much appreciated. Thanks

First of all 'Variables (8)' is not Id, its text. Id's are not dynamic since they represent unique identifier for the web element. 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.

What I understand from your question is you want to locate the <a> tag which contains text "Variables". Try using this 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"

You can try the below:

driver.findElement(By.cssSelector("a:contains('Variables')"));

If you want the word "Variables" , use the below:

String 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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