我正在尝试使用用于 javascript 的 selenium 网络驱动程序在我的网站上自动化测试。
我如何使用 wait 方法在此处运行测试,其中内容在页面加载时可能尚未准备好,例如数据来自外部 api 等?
在我的示例中,我的内容由外部 js 文件加载。您可以在 this fiddle 中查看页面的外观。我无法在下面的代码中链接它,因为 fiddle 被包裹在 iframe 中。
<head>
<script src="https://cdn.auth0.com/js/lock/10.2/lock.min.js"></script>
</head>
<body onload="lock.show();">
<div id="content">
<script type="text/javascript">
var domain = 'contoso.auth0.com';
var clientID = 'DyG9nCwIEofSy66QM3oo5xU6NFs3TmvT';
var lock = new Auth0Lock(clientID, domain);
lock.show({
focusInput: false,
popup: true,
}, function (err, profile, token) {
alert(err);
});
</script>
</div>
</body>
我可以使用 sleep 让它工作,但不能保证我的内容在超时结束后就绪。
const {Builder, By, Key, until} = require('selenium-webdriver');
let driver = new Builder()
.forBrowser('firefox')
.build();
driver.get('MY_URL')
driver.sleep(2000).then(function() {
driver.findElement(By.name('email')).sendKeys('test@test.com')
driver.findElement(By.name('password')).sendKeys('test')
//driver.findElement(By.className('auth0-lock-submit')).click()
})
但是如果我尝试等待
function login() {
return driver.findElement(By.name('email')).sendKeys('test@test.com')
}
driver.get('MY_URL')
driver.wait(login, 5000)
我收到 NoSuchElementError: Unable to locate element: *[name="email"]
我怎样才能让它工作,以便在继续之前等待我的内容可用。
最佳答案
隐式等待会告诉网络驱动程序在它抛出“没有这样的元素异常”之前等待一定的时间。默认设置为 0。一旦我们设置了时间,Web 驱动程序将在抛出异常之前等待该时间。
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
尝试使用FluentWait
。创建一个你想要等待的元素的 by 函数,并在下面的方法中传递它
WebElement waitsss(WebDriver driver, By elementIdentifier){
Wait<WebDriver> wait =
new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS) .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
return wait.until(new Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver driver) {
return driver.findElement(elementIdentifier);
}});
}
显式等待代码:
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[contains(.,'Next')]")));
引用:-
https://www.guru99.com/implicit-explicit-waits-selenium.html
关于javascript - 将等待与 selenium web 驱动程序异步内容一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45971748/