4 回答
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用 Fluent wait 來執(zhí)行此操作。這將檢查按鈕是否每5秒可單擊30秒。您可以根據(jù)需要調(diào)整時(shí)間。嘗試此代碼并提供反饋,無論它是否有效。
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement clickseleniumlink = wait.until(new Function<WebDriver, WebElement>(){
public WebElement apply(WebDriver driver ) {
return driver.findElement(By.xpath("//button[@id='btn_ok']"));
}
});
clickseleniumlink.click();
TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
試試這個(gè)方法??纯词欠裼袔椭?。
int size=driver.findElements(By.xpath("//button[@id='btn_ok']")).size();
if (size>0)
{
driver.findElement(By.xpath("//button[@id='btn_ok']")).click();
}
else
{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
int size1=driver.findElements(By.xpath("//button[@id='btn_ok']")).size();
if (size1>0)
{
driver.findElement(By.xpath("//button[@id='btn_ok']")).click();
}
}
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用顯式等待來等待按鈕可單擊。它將每500毫秒測試一次按鈕,最長為指定時(shí)間,直到它可點(diǎn)擊
WebDriverWait wait = new WebDriverWait(driver, 5); // maximum wait time is 5 here, can be set to longer time
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("btn_ok")));
button.click();
作為旁注,設(shè)置驅(qū)動(dòng)程序?qū)⑺阉髟氐淖铋L時(shí)間,它不會(huì)延遲腳本。implicitlyWait
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
我更喜歡這個(gè),因?yàn)樗梢圆扇∪魏尾紶枟l件來“等到”。
public static void WaitUntil(this IWebDriver driver, Func<bool> Condition, float timeout = 10f)
{
float timer = timeout;
while (!Condition.Invoke() && timer > 0f) {
System.Threading.Thread.Sleep(500);
timer -= 0.5f;
}
System.Threading.Thread.Sleep(500);
}
driver.WaitUntil(() => driver.FindElements(By.XPath("some xpath...").Length == 0);
//Here is the particular benefit over normal Selenium waits. Being able to wait for things that have utterly nothing to do with Selenium, but are still sometimes valid things to wait for.
driver.WaitUntil(() => "Something exists in the database");
我發(fā)現(xiàn)隱含的等待給我?guī)淼穆闊┍人膬r(jià)值更大。我發(fā)現(xiàn)顯式硒等待可能會(huì)變得有點(diǎn)冗長,并且它并沒有在我的框架中涵蓋我需要的所有內(nèi)容,所以我已經(jīng)進(jìn)行了大量的擴(kuò)展。這是其中之一。請注意,我在上面的示例中使用FindElements,因?yàn)槲也幌M谖凑业饺魏蝺?nèi)容時(shí)引發(fā)異常。這應(yīng)該適合您。
注意:這是C#,但是對于任何語言(尤其是Java)修改它應(yīng)該不難。如果您的語言不允許這樣的擴(kuò)展,只需在類中直接調(diào)用該方法即可。您需要將其放在靜態(tài)類中才能正常工作。在邏輯中像這樣擴(kuò)展現(xiàn)有類時(shí)要小心,因?yàn)楫?dāng)其他人試圖確定定義方法的位置時(shí),它可能會(huì)混淆。
添加回答
舉報(bào)
