4 回答

TA貢獻1785條經驗 獲得超8個贊
您可以使用 Fluent wait 來執行此操作。這將檢查按鈕是否每5秒可單擊30秒。您可以根據需要調整時間。嘗試此代碼并提供反饋,無論它是否有效。
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貢獻1725條經驗 獲得超8個贊
試試這個方法??纯词欠裼袔椭?。
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貢獻1799條經驗 獲得超8個贊
您可以使用顯式等待來等待按鈕可單擊。它將每500毫秒測試一次按鈕,最長為指定時間,直到它可點擊
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();
作為旁注,設置驅動程序將搜索元素的最長時間,它不會延遲腳本。implicitlyWait

TA貢獻1780條經驗 獲得超1個贊
我更喜歡這個,因為它可以采取任何布爾條件來“等到”。
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");
我發現隱含的等待給我帶來的麻煩比它的價值更大。我發現顯式硒等待可能會變得有點冗長,并且它并沒有在我的框架中涵蓋我需要的所有內容,所以我已經進行了大量的擴展。這是其中之一。請注意,我在上面的示例中使用FindElements,因為我不希望在未找到任何內容時引發異常。這應該適合您。
注意:這是C#,但是對于任何語言(尤其是Java)修改它應該不難。如果您的語言不允許這樣的擴展,只需在類中直接調用該方法即可。您需要將其放在靜態類中才能正常工作。在邏輯中像這樣擴展現有類時要小心,因為當其他人試圖確定定義方法的位置時,它可能會混淆。
添加回答
舉報