selenium - FindBy 属性何时触发 driver.FindElement?

标签 selenium selenium-webdriver webdriver pageobjects

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

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

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

最佳答案

WebElements 被懒惰地评估。也就是说,如果您从不使用 PageObject 中的 WebElement 字段,则永远不会为它调用“findElement”。 Reference .

如果不想WebDriver每次要查询元素,你必须使用@CacheLookup注解。

What about the list part of my question?



当您从列表中查询时会触发 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类(class)。我建议深入研究来源以获得答案。

您可能会发现 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
   */

关于selenium - FindBy 属性何时触发 driver.FindElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723730/

相关文章:

python - 如何使用 python selenium 单击弹出窗口中的按钮?

python - 在 python selenium 中,如何找到元素的可见性?

xpath - 如何创建 XPath 查询来提取文本子字符串?

javascript - 如何使 Protractor 中的自动化测试脚本等待,直到页面完全加载

java - 在哪里查看哪个 JXBrowser 和 Selenium 匹配的版本?

java - 使用 Nightwatch 测试 Node.js 项目时如何在 Travis CI 上运行 Selenium Server

java - 当 Selenium WebDriver.get() 加载的页面为空并弹出登录警报时,它会卡住

javascript - 如何等到元素的文本在 WebdriverJS 中发生变化?

python - Python 中的正则表达式查找表中的行

selenium - 检查是否出现 "Please enter an email address"消息