如何使用C#获得Selenium元素列表
本文关键字:元素 列表 Selenium 获得 何使用 | 更新日期: 2023-09-27 18:00:09
我正在尝试在Selenium中列出web元素。我现在的问题是,有4个gif都可以点击,但都具有相同的值。我需要把它们列一个清单,这样我就可以选择我想要的。这是我的代码行
List<IWebElement> createGifs = driver.FindElements(By.XPath("//img[@ src='images/document_create.gif']"));
我在网上看到的每一个地方都有这个合适的答案。然而,我收到的错误:
错误1无法将类型"System.Collections.ObjectModel.ReadOnlyCollection"隐式转换为"System.Collections.Generic.List"
有人知道如何实现我想要的目标,或者如何绕过这个错误吗?
将其转换为ReadOnlyCollection
,并确保您有using System.Collections.Generic;
导入
IReadOnlyCollection<IWebElement> createGifs = driver.FindElements(By.XPath("//img[@ src='images/document_create.gif']"));
如果您确实想使用List
,则使用ToList()
List<IWebElement> createGifs = driver.FindElements(By.XPath("//img[@ src='images/document_create.gif']")).ToList();
编辑
To Clarify Selenium的ISearchContext.FindElements
方法默认返回ReadOnlyCollection<IWebElement>
。请参阅此
您可以将IReadOnlyCollection
转换为List。
例如,如果您正在搜索li
,则应该执行以下操作。
//get readonly list
IReadOnlyCollection<IWebElement> li_element_list =driver.FindElements(By.TagName("li"));
//create new list
List<IWebElement> allHandles2 = new List<IWebElement>(li_element_list);
List<IWebElement> createGifs = new List<IWebElement> (driver.FindElements(By.XPath("//img[@ src='images/document_create.gif']")));
这对我来说很好。