1

So I believe I am able to grab the element via CSS Selector or Xpath and even by TagName but I am unable to grab the text that is associated with it.

Here is what the HTML looks like:

<label for="AnswerText">This is the question text? </label>

In my code I have this:

static IWebDriver driver = new ChromeDriver(".");
static IWebElement securityQuestion = driver.FindElement(By.TagName("label"));

Console.WriteLine("question is ", securityQuestion.Text)

What I want to be able to do is grab this text from the label "This is the question text?". Im doing this because the text changes and depending on the answer the Input will be different so I have to incorporate logic in order to grab that text and set it equal to a variable to match against.

I have tried .Text GetAttribute("value") but that wont work because labels do not have any value as well as different selectors.

static IWebDriver driver = new ChromeDriver(".");
static IWebElement securityQuestion = driver.FindElement(By.TagName("label"));

Console.WriteLine("question is ", securityQuestion.Text)
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Tabish
  • 11
  • 2

2 Answers2

-1

To extract the text This is the question text? you have to induce WebDriverWait for the ElementIsVisible() and GetAttribute("innerHTML") and you can use either of the following Locator Strategies:

  • CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("label[for='AnswerText']"))).GetAttribute("innerHTML");;
    
  • XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//label[for='AnswerText']"))).GetAttribute("innerHTML");
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • This didn't work. I still get the same issue of not being able to grab the text with no errors. – Tabish Jun 17 '19 at 14:03
-1

I don't have enough rep to comment yet, but what you have should work. Makes me wonder if you are getting the correct element. What is the exception/output when you try to print the Text? I am assuming there is more than one element with the TagName "label" on the page. I would try to find a more unique parent element and then get the child element that has the text your looking for.

 IWebElment elem = driver.FindElement(By.Id("ParentID")).FindElement(By.TagName("label"));

Or try with XPath... maybe the path you try before was incorrect. If you provide some more of the Html, I can try to help.

Raoul Duke
  • 127
  • 7