Reputation: 13
I try to find a proper way to do below operation:
IWebElement content = driver.FindElementByXPath( myXPath );
while(true)
{
if ( !content.Text.Equals ( driver.FindElementByXPath ( myXPath ).Text ) )
{
content = driver.FindElementByXPath ( myXPath );
Console.WriteLine ( content.Text );
}
}
My code prints content on myXPath when content changed. But obviously, it is not a effective way. Is there any proper method to listen changes on a XPath location?
Upvotes: 1
Views: 1672
Reputation: 324
Your while loop takes most of your CPU usage a small change can upgrade your performance significantly.
while(true)
{
if ( !content.Text.Equals ( driver.FindElementByXPath ( myXPath ).Text ) )
{
content = driver.FindElementByXPath ( myXPath );
Console.WriteLine ( content.Text );
Thread.Sleep(1); //add this code
}
}
I would suggest the following method:
public bool StopWatchLoop<T>(Func<string, T> getMethod, string getData, T cond) where T : new()
{
var i = getMethod(getData);
var sw = new Stopwatch();
sw.Start();
while (Compare(i, cond) && sw.Elapsed < TimeSpan.FromSeconds(120))
{
i = getMethod(getData);
Thread.Sleep(50);
}
Trace.WriteLine($"Expected: {cond.ToString()} actual {i} - data: {getData}");
return (Compare(i, cond)) ? true : false;
}
private bool Compare<T>(T x, T y)
{
return EqualityComparer<T>.Default.Equals(x, y);
}
In your case. the get method used as a sampler and the cond variable is your expced text
so now you can use:
StopWatchLoop<string>(getElementText, myXpath, Content.Text);
The code above samples the element for maximum time of 120 seconds since while(true) is bad practice.
Upvotes: 2