看来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“,然后在结果页面上转到图像结果。
对于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做特例吗?
发布于 2017-08-02 21:22:28
基本上,当您尝试在页面上“单击”或“sendKeys”时,Selenium就会爆炸。
(我确信存在默认的隐式等待,但我不确定它是什么)。基本上,这取决于您如何确定您希望测试在失败之前等待它们的灵活性。我希望这能帮到你。
显式等待示例:
@Test
public void testGoogleSearch() {
driver.get("http://duckduckgo.com");
By searchInputBy = By.id("search_form_input_homepage");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(searchInputBy));
driver.findElement(searchInputBy).sendKeys("Hello World");
driver.findElement(By.id("search_button_homepage")).click();
wait = new WebDriverWait(driver, 10);
By imagesBy = By.linkText("Images");
wait.until(ExpectedConditions.elementToBeClickable(imagesBy));
driver.findElement(imagesBy).click();
} 隐式等待示例:
@Test
public void testGoogleSearch() {
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
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();
}您还可以选择使用fluent等待,这使您能够更好地控制显式等待,因此您可以告诉它忽略某些异常,但它们更冗长。
我认为创建一个静态方法库来完成fluent等待的繁重工作是一种更好、更易读、更易于编写测试的方法。
另外,一个伟大的答案解释了更多的细节。
发布于 2017-08-03 09:09:35
根本原因是您的代码不等待搜索结果。您可以使用WebDriverWait和ExpectedConditions来等待images链接。见下面的一个例子。
@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();
WebDriverWait waiter = new WebDriverWait(driver,20);
WebElement imagesLink = waiter.until(ExpectedConditions.elementToBeClickable(By.linkText("Images")));
imagesLink.click();
}https://stackoverflow.com/questions/45469174
复制相似问题