繁体   English   中英

使用C#(Selenium)从数组获取随机元素的文本

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

这是我的Selenium页面对象的一种方法(该页面在此处称为“ LandingPage_Page”)-此方法旨在获取1个元素的文本,但窍门是,该元素是从包含12个页面的页面中随机选择的类似元素。 我希望它每次运行时都能从这12个元素中获取不同的元素。

    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; 

最终=之后的所有内容均以红色突出显示。 错误消息:“无法将类型'string'隐式转换为'System.Collections.ObjectModel.ReadOnlyCollection”

是articleThumbTitle数组吗? 我希望它是...如果是,我是否将随机数正确地调用到数组中?

预先感谢您的指导,Y。

您应该像这样访问Text属性:

 string articleThumbTitleText = articleThumbTitle[rInt].Text;   

文本是为IWebElement定义的属性。 因此,您不能将其用作方法。

这是错误的答案,Driver.findelements将返回一个列表,因此articleThumbTitle是类型为list的对象,您无法为其分配字符串文本值。 像这样更改它:

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

我还建议您检查articleThumbTitle.Count()<11。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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