Java 是否可以通过具有WebElement的对象获取

Java 是否可以通过具有WebElement的对象获取,java,selenium,Java,Selenium,我正在使用@FindBy注释来定位WebElements。但是我想在方法中使用这些WebElement作为参数。只有在页面上找到WebElement,我才能成功地使用它。但如果我想等待它,我必须使用By(使用相同的定位器) 例如 这样,我就可以在某些方法中使用这个WebElement作为By对象,比如 public boolean isElementDisplayedWithWait(final By by) { .... } 对于每个元素,我有4行代码。我很懒,正在寻找一种方法来简化它。在中

我正在使用@FindBy注释来定位WebElements。但是我想在方法中使用这些WebElement作为参数。只有在页面上找到WebElement,我才能成功地使用它。但如果我想等待它,我必须使用By(使用相同的定位器)

例如

这样,我就可以在某些方法中使用这个WebElement作为By对象,比如

public boolean isElementDisplayedWithWait(final By by) { .... }

对于每个元素,我有4行代码。我很懒,正在寻找一种方法来简化它。

在中的扩展webelement中,可以使用webelement本身的等待/断言/验证方法。例如:

@FindBy(css = SEARCHFIELD_LOC)
public WebElement searchField;

searchField.waitForPresent();
searchField.assertPresent(); //auto wait
searchField.verifyPresent(); //auto wait
参考:


  • 我找到了完全不同的解决办法。我将把定位器存储为字符串

    public String searchField = ".slide.slide_search input[placeholder]"
    
    所以每个定位器只有一行代码。我希望只支持CSS定位器就足够了。我不会使用@FindBy获取WebElements。相反,我将使用特殊的方法获取WebElements,该方法将等待element并记录正在发生的事情。我将实现如下方式获取WebElement:

    WebElement we = wait.until(ExpectedConditions.visibilityOfElementLocated(new By.ByCssSelector(locator)));
    
    等待在哪里

    Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
                    .withTimeout(timeout, TimeUnit.SECONDS)
                    .pollingEvery(1, TimeUnit.SECONDS)
                    .ignoring( StaleElementReferenceException.class ) ;
    
    Wait Wait=new FluentWait(驱动程序)
    .withTimeout(超时,时间单位为秒)
    .轮询间隔(1,时间单位。秒)
    .忽略(StaleElementReferenceException.class);
    
    谢谢,但我现在不想使用任何框架。
    Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
                    .withTimeout(timeout, TimeUnit.SECONDS)
                    .pollingEvery(1, TimeUnit.SECONDS)
                    .ignoring( StaleElementReferenceException.class ) ;