[英]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. 这是我的Selenium页面对象的一种方法(该页面在此处称为“ LandingPage_Page”)-此方法旨在获取1个元素的文本,但窍门是,该元素是从包含12个页面的页面中随机选择的类似元素。 I want it to grab a different element from those 12 each time the test runs.
我希望它每次运行时都能从这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;
Everything after the final = is highlighted in red. 最终=之后的所有内容均以红色突出显示。 The error says: "Cannot implicitly convert type 'string' to 'System.Collections.ObjectModel.ReadOnlyCollection"
错误消息:“无法将类型'string'隐式转换为'System.Collections.ObjectModel.ReadOnlyCollection”
Is articleThumbTitle an array? 是articleThumbTitle数组吗? I want it to be... If so, am I calling the random number into the array correctly?
我希望它是...如果是,我是否将随机数正确地调用到数组中?
Thanks in advance for any guidance, Y. 预先感谢您的指导,Y。
You should access Text property like this : 您应该像这样访问Text属性:
string articleThumbTitleText = articleThumbTitle[rInt].Text;
Text is property defined for IWebElement. 文本是为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. 这是错误的答案,Driver.findelements将返回一个列表,因此articleThumbTitle是类型为list的对象,您无法为其分配字符串文本值。 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. 我还建议您检查articleThumbTitle.Count()<11。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.