I am trying to return the last element with the class name MyClass. I am using selenium, but the following code does not work. I am not sure if I am setting it up correctly.
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
Console.WriteLine((string)js.ExecuteScript(".MyClass:last-child"));
If you are using C# as the tag in your question indicates, you don't need JSE. One way to do this is to use LINQ
using System.Collections.ObjectModel;
using System.Linq;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector(".MyClass"));
IWebElement lastElement = elements.ElementAt(elements.Count - 1);
string lastElementText = lastElement.Text;
Just for fun try...
string lastElementText = driver.FindElement(By.CssSelector(".MyClass:last-child")).Text;
NOTE: Turns out this doesn't work... it returns the text of the first element. I'm assuming that :last-child
is not supported.
From a further discussion, OP wanted to get the text of the last element and then know when it changes (within a few seconds). This code should take care of that case...
By locator = By.CssSelector(".MyClass");
ReadOnlyCollection<IWebElement> elements = driver.FindElements(locator);
IWebElement lastElement = elements.ElementAt(elements.Count - 1);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(d => d.FindElement(locator).Text != lastElement.Text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.