一尘不染

FindBy属性何时触发driver.FindElement?

selenium

我的问题是:装饰有findby属性的Webelements是否在每次引用它们时调用findelement函数?如果没有,什么时候?

用List 装饰的程序是什么?当您引用列表或引用列表中的元素时,它会触发吗?

我之所以问是因为,在某些情况下,我会遇到过时的元素异常,并且我想知道如何处理它们。


阅读 315

收藏
2020-06-26

共1个答案

一尘不染

WebElement的计算是惰性的。也就是说,如果您从不在PageObject中使用WebElement字段,则永远不会调用它的“
findElement”。参考

如果不想WebDriver每次都查询元素,则必须使用@CacheLookup注释。

那我的问题清单部分呢?

从列表中查询时将触发findElements。说您有:

@FindBy(xpath = "//div[@class=\"langlist langlist-large\"]//a")
private List<WebElement> list;

以下代码示例均 触发 findElements:

list.isEmpty();

WebElement element = list.get(0);

在哪里

List<WebElement> newList = new ArrayList<WebElement>();
newList = list;

不会触发 findElements()。

请检查LocatingElementListHandler课程。我建议深入探讨答案。


您可能会发现PageFactory类中的以下代码注释有帮助:

/**
   * Instantiate an instance of the given class, and set a lazy proxy for each of the WebElement
   * and List<WebElement> fields that have been declared, assuming that the field name is also
   * the HTML element's "id" or "name". This means that for the class:
   * 
   * <code>
   * public class Page {
   *     private WebElement submit;
   * }
   * </code>
   * 
   * there will be an element that can be located using the xpath expression "//*[@id='submit']" or
   * "//*[@name='submit']"
   * 
   * By default, the element or the list is looked up each and every time a method is called upon it.
   * To change this behaviour, simply annotate the field with the {@link CacheLookup}.
   * To change how the element is located, use the {@link FindBy} annotation.
   * 
   * This method will attempt to instantiate the class given to it, preferably using a constructor
   * which takes a WebDriver instance as its only argument or falling back on a no-arg constructor.
   * An exception will be thrown if the class cannot be instantiated.
   * 
   * @see FindBy
   * @see CacheLookup
   * @param driver The driver that will be used to look up the elements
   * @param pageClassToProxy A class which will be initialised.
   * @return An instantiated instance of the class with WebElement and List<WebElement> fields proxied
   */
2020-06-26