Can I use a string variable when using LinkText?

421 Views Asked by At

Using Selenium in Visual Studio. I'm trying to click on a item in a list. The item has a unique ID.

CA-41107005-00000040

Instead of referring to the actual ID-number I want to make the test more dynamic by referring to a string variable that will store a item ID. I call this variable: changeActionNumber

The HTML code for the item looks like this: enter image description here

I have tried clicking on the item like this:

wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText($"{changeActionNumber}"))).Click();

And also like this:

wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText(changeActionNumber))).Click();

But both cases gave the same error:

Message: OpenQA.Selenium.WebDriverTimeoutException : Timed out after 10 seconds
  ----> OpenQA.Selenium.NoSuchElementException : no such element: Unable to locate element: {"method":"link text","selector":"CA-41107005-00000040"}
  (Session info: chrome=77.0.3865.75)

Is it not possible to use variables when using LinkText?

3

There are 3 best solutions below

0
On BEST ANSWER

Using variables in LinkText was not the problem.

The problem was that my driver was not focused on the correct iframe and could therefore never find a matching LinkText value.

I changed my iframe focus like this:

driver.SwitchTo().DefaultFrame();

driver.SwitchTo().Frame("firstiframe");
driver.SwitchTo().Frame("secondiframe");
driver.SwitchTo().Frame("thirdiframe");
driver.SwitchTo().Frame("ECMMyChangeActions");

And after that I could use LinkText with a variable without any problem.

0
On

AFAIK, LinkText selector looks for link text as it is presented on page, not in html code. So if this text is additionally formatted before being displayed on page, like letters to lower case or special symbols removed, you must consider this.

If you want to work with text as it presented in code, try xpath instead

By.XPath(string.Format(".//a[.='{0}']", changeActionNumber))
1
On

Try the below xapth

wait.Until(ExpectedConditions.ElementToBeClickable(By.Xpath("//a[text()='" +changeActionNumber + ']"))).Click();

OR

wait.Until(ExpectedConditions.ElementToBeClickable(By.Xpath("//a[contains(.,'" +changeActionNumber + ')]"))).Click();