看來,Selenium的SafariDriver不會等待網頁加載。我的測試如下:Selenium SafariDriver不會等待頁面加載?
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.safari.SafariDriver;
public class SafariTest {
private WebDriver driver;
@Before
public void setUp() throws Exception {
driver = new SafariDriver();
}
@After
public void tearDown() throws Exception {
driver.close();
}
@Test
public void testGoogleSearch() {
driver.get("http://duckduckgo.com");
driver.findElement(By.id("search_form_input_homepage")).sendKeys("Hello World");
driver.findElement(By.id("search_button_homepage")).click();
driver.findElement(By.linkText("Images")).click();
}
}
如果你運行這個與ChromeDriver
,或FirefoxDriver
,它的功能,因爲它應該,即它搜索的「Hello World」,然後在結果頁面上,這是不言而喻的圖像效果。
隨着SafariDriver
,它失敗:
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters. (WARNING: The server did not provide any stacktrace information)
不能被發現是「圖像」,因爲之前跑了聲明的頁面沒有加載的元素。
這是預期的行爲?我應該爲Safari特例嗎?
這可能是Safari瀏覽器在某些方面只是比較慢,導致此頁面出現問題。一般來說,你應該使用** [顯式等待](https://stackoverflow.com/questions/10404160/when-to-use-explicit-wait-vs-implicit-wait-in-selenium-webdriver)** 。或者我猜**如果你想鎖定自己沒有靈活性使用**顯式等待**,則隱式等待**,因爲硒文檔由於意外的等待時間而警告不要混合它們。 – mrfreester
@mrfreester爲什麼應該顯式等待? – Roxy
**如果使用隱式等待**,應該只在測試套件開始時設置一次。但是,通常人們會在測試套件中改變它們,這在將來的測試等待時間和難以追蹤的微小錯誤中導致不可預測性。 **隱式等待**也只等待元素爲__exist__,這並不總意味着元素已準備好與之交互。通過**顯式等待**,您可以清楚地表明您正在等待**可見**,**可點擊**或其他任何您想要的內容,從而使您的測試更加清晰穩定。 – mrfreester