什么时候FindBy属性触发driver.FindElement?

Ser*_*scu 5 selenium webdriver pageobjects selenium-webdriver

我的问题是:使用findby属性修饰的webelements是否在每次引用时调用findelement函数?如果不是,何时?

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

我问,因为我有一些情况,我得到陈旧的元素异常,我想知道如何处理它们.

Erk*_* M. 3

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

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

我的问题的列表部分怎么样?

当您从列表中查询时,会触发 findElements。假设你有:

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

以下代码示例都会触发findElements :

list.isEmpty();
Run Code Online (Sandbox Code Playgroud)

WebElement element = list.get(0);

然而

List<WebElement> newList = new ArrayList<WebElement>();
newList = list;
Run Code Online (Sandbox Code Playgroud)

不会触发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
   */
Run Code Online (Sandbox Code Playgroud)