Reputation: 1786
I am trying to fetch the Text of All table rows in a web page using Selenium C#. Below is the code for retriving all tr's from the web page:
var trElements = driver.FindElements(By.TagName("tr"));
This shows the data correctly. For example, tr element number 35 has text 'canara bank' in it, that can be seen in below image.
Now I am trying to extract only text of all the tr elements. Either by using LINQ or by using for loop:
string[] strrr= trElements.Select(t => t.Text).ToArray();
Surprisingly, Text property of most of the element does not show up the data that was shown in web element. Randomly data of some elements keeps showing up or goes off.
I want to ensure that data of web elements is correctly converted to string array. How to achieve this?
Upvotes: 0
Views: 122
Reputation: 5137
I think there are 3 possibilities.
1. The rows are not visible. So element.Text can't give you the text. In this case, you need to use element.GetAttribute("innerText")
instead of element.Text
.
string[] strrr = trElements.Select(t => t.GetAttribute("innerText")).ToArray();
2. The script does not have enough wait time. In this case, you just need to add wait to check text length.
var trElements = driver.FindElements(By.TagName("tr"));
List<string> strrr = new List<string>();
foreach (var tr in trElements)
{
IWait<IWebElement> wait = new DefaultWait<IWebElement>(tr);
wait.Timeout = TimeSpan.FromSeconds(10);
try
{
wait.Until(element => element.Text.Trim().Length > 1);
strrr.Add(element.Text.Trim());
}
catch (WebDriverTimeoutException)
{
strrr.Add("");
}
}
3. The text will be displayed when you scroll down.
int SCROLL_PAUSE_TIME = 1;
int SCROLL_LENGTH = 500;
var jsExecutor = driver as IJavaScriptExecutor;
int pageHeight = Int32.Parse((string)jsExecutor.ExecuteScript("return document.body.scrollHeight"));
int scrollPosition = 0;
while (scrollPosition < pageHeight)
{
scrollPosition = scrollPosition + SCROLL_LENGTH;
jsExecutor.ExecuteScript("window.scrollTo(0, " + scrollPosition + ");");
System.Threading.Thread.Sleep(SCROLL_PAUSE_TIME);
}
var trElements = driver.FindElements(By.TagName("tr"));
Upvotes: 1