Selenium Webdriver 和 PageFactory 初始化 List<WebElement> 元素

Posted

技术标签:

【中文标题】Selenium Webdriver 和 PageFactory 初始化 List<WebElement> 元素【英文标题】:Selenium Webdriver and PageFactory initialize List<WebElement> elements 【发布时间】:2011-12-21 22:18:32 【问题描述】:

我搜索了托管在谷歌代码上的 Selenium Webdriver APi 文档。目前使用 PageFactory 来初始化我的 Page 对象,但在初始化 WebElement 列表时遇到问题。

我需要的是一种初始化元素列表的方法,最好是下拉选择框列表。

我查看了对 @Findsby 和 @ByChained 的 API 引用,但仍然无法找出初始化下拉选择框列表的最佳方法。我可以为每个 WebElement 设置一个单独的 WebElement 并获取 ID,但我想初始化一个列表选择列表

目前我使用以下:

public class PageObject 

        @FindBy(id="element_id")
        private WebElement element;

        public getElement() 
          return element;
        

有什么方法可以使用类似于我所寻求的以下内容:

public class PageObject    

    @FindBys(className="selectItmes")
    private List<WebElement> selects;

    public List<WebElement> getSelects() 
      return selects;
      

或者我必须为每个元素使用一个 Web 元素吗? :(

更新

任何人都知道如何使用 PageFactory 并初始化 List 元素;使用 FindsBy 注释。我找不到任何这样做的方法,但是 selenium google docs 网站上的谷歌问题说这已经在 J​​ava api 绑定和 2.12 版本中得到修复,因为它在 2.11 中被错误地禁用了......我仍然可以' t 初始化一个列表。 =/

【问题讨论】:

【参考方案1】:

最近在 Selenium 2.0 中添加了此功能。检查此issue。现在已经修复了。

从文档中,您可以执行以下操作,

@FindAllBy(className="selectItmes") 
List<WebElement> selects;

如果您对代码感兴趣,请查看this out

【讨论】:

感谢您的回复 nilesh! 事实证明它已从版本中删除,因为它导致了其他问题。 link :( 当我用 maven 存储库 2.11 版的当前 selenium 版本更新我的 pom 文件时,我感到很沮丧 本周将发布一个新版本。敬请期待! 我正在使用 Selenium Webdriver .Net 绑定的最新库文件,但仍然无法使用 [FindBy(How = How.Id, Using = "id")] public List 元素 获取;放;我收到以下错误:消息:System.ArgumentException:“Castle.Proxies.IWrapsElementProxy_1”类型的对象无法转换为“System.Collections.Generic.List`1[OpenQA.Selenium.IWebElement]”类型。 这是什么状态? Selenium 2.25.0 没有这个类。【参考方案2】:

这是我在我们的测试框架中所做的标准解决方案,直到 @FindAllBy 在 Selenium 库中不起作用:

private List<WebElement> selects;

public List<WebElement> getSelects() 
      selects = getDriver().findElements(By.xpath("..."));
      return selects;
     

【讨论】:

【参考方案3】:

您可以很容易地找到选择选项,您所要做的就是使用 Webdriver.Support dll 参考。这使您可以访问 SelectElement 类。这是一个简单的例子:

IWebElement element = driver.FindElement(By.TagName("select"));

SelectElement select = new SelectElement(element);
int options = element.FindElements(By.TagName("option")).Count();
select.SelectByIndex(new Random().Next(1, options - 1));

上面的代码找到了选择元素,获取了该选择元素中选项的计数,然后随机选择一个。

代码可能略有不同,因为我的代码是用 C# 编写的

【讨论】:

【参考方案4】:
      @FindBys(@FindBy(xpath="//span[@class='ng-binding']"))

        private List<WebElement> AllData;

        public List<WebElement> getAllData() 
            return AllData;
        

【讨论】:

【参考方案5】:

我这样解决这个问题:

@FindBy(id="element_id")
public List<WebElement> selects;

您现在拥有具有该 ID 的所有 Web 元素的列表。

然后,您只需像抓取任何其他 PageFactory WebElement 列表一样从列表中抓取元素。

【讨论】:

以上是关于Selenium Webdriver 和 PageFactory 初始化 List<WebElement> 元素的主要内容,如果未能解决你的问题,请参考以下文章

selenium webdriver设置超时

selenium调用webdriver异常

(java)selenium webdriver学习---实现简单的翻页,将页面内容的标题和标题链接取出

爬虫之selenium和webdriver—基础

如何使用Selenium Webdriver和Java编写定位器来单击img?

Selenium PhantomJS webdriver获得部分截图