2013-05-29 73 views
2

如何從WebElement獲取Findby類型和字符串?如何從WebElement獲取Findby類型和字符串

我正在使用自建的webDriverWait函數,該函數將能夠接收By或Webelement以用於presenceOfElementLocated()函數。

定義WebElement

@FindBy(xpath = "//div[@id='calendar-1234']") 
private WebElement calander; 

的兩個webDriverWaitFor功能
第一個使用由和工作沒關係:,第二個使用webElement

public void webDriverWaitFor(WebDriver driver, By by) throws ElementLocatorException { 
    try{ 
     (new WebDriverWait(driver, 5)) 
     .until(ExpectedConditions.presenceOfElementLocated(by)); 
    } 
    catch (Exception e) { 
     throw new ElementLocatorException(by); 
    } 

} 

第二個使用WebElement我正在嘗試獲取By類型和字符串。 這implimintation不好:By.id(webElement.getAttribute( 「ID」))

public void webDriverWaitFor(WebDriver driver, WebElement webElement) throws ElementLocatorException { 
    try{ 
     (new WebDriverWait(driver, 5)) 
     .until(ExpectedConditions.presenceOfElementLocated( By.id(webElement.getAttribute("id")))); 
    } 
    catch (Exception e) { 
     throw new ElementLocatorException(By.id(webElement.getAttribute("id"))); 
    } 

} 

我如何能夠實現以下?

webDriverWaitFor(driver, calander); 

回答

0

通常您可以撥打element.toString()並解析它。返回的字符串包含所有必要的信息。

但它不會在你的情況下工作,因爲只有在實例化WebElement後才能獲取此信息。您正在使用@FindBy標記,這意味着您將嘗試使用該元素時將查找該元素。你的例子不起作用,因爲你嘗試調用webElement.getAttribute時,driver.findBy被內部調用,並且由於該元素尚不存在而失敗。

我能想到的唯一的辦法是寫自己的wait方法

public boolean isElementPresent(WebElement element) { 
    try { 
     element.isDisplayed(); // we need to call any method on the element in order to force Selenium to look it up 
     return true; 
    } catch (Exception e) { 
     return false; 
    } 
} 

public void webDriverWaitFor(WebElement element) { 
    for (int second = 0; ; second++) { 
     if (second >= 60) { 
     //element not found, log the error 
     break; 
     } 
     if (isElementPresent(element)) { 
     //ok, we found the element 
     break; 
     } 
     Thread.sleep(1000); 
    } 
} 

如果您使用隱式等待這個例子將不能很好地工作,但(每次嘗試調用element.isDisplayed就要花費很多的時間)!

+0

如何使用pagefactory編寫自定義'isElementPresent'。如果沒有pagefactory它是這樣寫的: '嘗試{ \t \t \t如果(driver.findElements(定位).size()> 0){ \t \t \t \t迴歸真實; \t \t \t} else \t \t \t \t return false; \t \t} \t \t趕上(例外五){ \t \t \t返回假; \t \t}' – paul

相關問題