有一次,我發現自己在同樣的情況你。另外,我有很多實際發現的元素,但都不可見 - JSF還不夠快,無法讓它們可見。另外,我厭倦了一次又一次地寫selenium
。
於是我坐下來,寫了下面的代碼。它等待所有元素出現在頁面上並且在與它們交互之前可見(或者在超時後失敗)。因爲我已經搬到了webdriver的,所以我沒有原代碼,但它是這樣的:
public static long WAIT = 10000; // ten seconds
private void waitForElement(String locator) {
long targetTime = System.currentTimeMillis() + WAIT;
boolean found;
do {
found = selenium.isElementPresent(locator) && selenium.isVisible(locator);
} while (!found && (targetTime < System.currentTimeMillis()));
if (!found) {
throw new SeleniumException("Element " + locator + " not found");
}
}
public void click(String locator) {
waitForElement(locator);
selenium.click(locator);
}
public void type(String locator, String text) {
waitForElement(locator);
selenium.type(locator, text);
}
至於waitForCondition()
這應該是一個代碼檢測一個元素是否存在:
String locator = "id=anything";
String script =
"var retValue = true;" +
"try {" +
" selenium.browserbot.findElement('" + locator + "');" +
"} catch(e) {" +
" retValue = false;" +
"}" +
"retValue;";
selenium.waitForCondition("!!selenium.browserbot.findElement('" + locator + "')", "10000");
selenium.click(locator);
,只是普通的JavaScript:
var retValue = true;
try {
selenium.browserbot.findElement('" + locator + "');
} catch(e) {
retValue = false;
}
retValue;