Search code examples
c#stringvisual-studioseleniumlinktext

Can I use a string variable when using LinkText?


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?


Solution

  • 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.