Reputation: 21960
I want to read the text next to an input item with C#.
This is my HTML:
<p id="mpNames">
<input id="selectMp1" type="checkbox">
"Text next to the input element"
This is my code:
var inputWeList = drv.FindElements(By.CssSelector("#mpNames > input"));
foreach (var inputItem in inputWeList)
{
var inputItemText = inputItem.GetAttribute("value"); // gives "on"
...
}
My second try:
var inputWeList = drv.FindElements(By.CssSelector("#mpNames > input"));
foreach (var inputItem in inputWeList)
{
var inputItemText = inputItem.Text(); // gives ""
...
}
How do I get "Text next to the input element"?
Upvotes: 1
Views: 1762
Reputation: 5137
You need to get them by JavaScript because the text are under the same parent. JavaScript need to walk through child nodes of the < id="mpNames"
and returns all child nodes which are text nodes. See my example below.
var script = @"function getTextNode(rootNode) {
var nodes = rootNode.childNodes;
var fieldNames = [];
var count=0;
for (var i = 0; i < nodes.length; i++) {
if ((nodes[i].nodeType == Node.TEXT_NODE)) {
let text = nodes[i].textContent.trim();
fieldNames[count++] = text;
}
}
return fieldNames;
}";
var results = (drv as IJavaScriptExecutor).ExecuteScript(script) as List<string>;
results.ForEach(txt => System.Diagnostics.Debug.WriteLine(txt));
Upvotes: 0
Reputation: 193108
Seems the text "Text next to the input element"
is out of the <input>
tag. So instead of :
var inputWeList = drv.FindElements(By.CssSelector("#mpNames > input"));
You can try :
var inputWeList = drv.FindElements(By.XPath("//p[@id='mpNames' and not(@type='checkbox')]"));
Upvotes: 1
Reputation: 29026
Make use of inputItem.InnerHtml
or inputItem.innerText
instead for GetAttribute("value");
and .Text()
, Here is the difference between both:
Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the same content but in HTML format
Upvotes: 1