简体   繁体   中英

Get text of random element from an array using C# (Selenium)

This is a method for my Selenium page object (the page is referred to here as "LandingPage_Page") - this method is meant to get the text of 1 element, but the trick is, that element is chosen randomly from a page that contains 12 similar elements. I want it to grab a different element from those 12 each time the test runs.

    public LandingPage_Page ArticleThumbnailTitle()
    {
        Random r = new Random();
        int rInt = r.Next(0, 11);

        var articleThumbTitle = Driver.FindElements(By.CssSelector(".row .article-title"));
        articleThumbTitle = articleThumbTitle[rInt].Text;            

        return this; 

Everything after the final = is highlighted in red. The error says: "Cannot implicitly convert type 'string' to 'System.Collections.ObjectModel.ReadOnlyCollection"

Is articleThumbTitle an array? I want it to be... If so, am I calling the random number into the array correctly?

Thanks in advance for any guidance, Y.

You should access Text property like this :

 string articleThumbTitleText = articleThumbTitle[rInt].Text;   

Text is property defined for IWebElement. So, you can't use it as method.

This is incorrect Yan, Driver.findelements will return a list so articleThumbTitle is an object of type list you can not assign a string text value to it. Change it like this:

var articleThumbTitle = Driver.FindElements(By.CssSelector(".row .article-title"));
var randomText = articleThumbTitle[rInt].Text;

I'd also recommend you check that articleThumbTitle.Count() < 11.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM