我正在尝试执行一项相对简单的任务:WAITING页面重定向完成。刚刚看到another回答了有关该主题的问题,建议是等待后一页上的特定文本出现(如果我做对了)。如果是这样,等到 window.location
发生变化怎么样?好点吗?更差?不太适用?还有其他想法吗? 只是好奇,如果需要,可以将此问题标记为社区 wiki。
谢谢!
最佳答案
是的,我在使用 Selenium 时遇到过很多次这个问题。我有两种方法解决这个问题。首先,您实际上可以更改隐式等待时间。例如给定这段代码:
Actions builder = new Actions( driver );
builder.click( driver.findElement( By.className("lala") ) ).perform();
如果在调用它的时候没有找到与“lala”类匹配的元素,则此代码将抛出异常。您可以通过以下方式更改此隐式等待时间:
driver.manage().timeouts().implicitlyWait( 5, TimeUnit.SECONDS );
这使得驱动程序轮询 5 秒而不是立即失败。如果 5 秒后仍无法定位该元素,则该操作将失败。当然,您可以更改该设置。我发现这种方法在大多数情况下都可以正常工作。大多数时候,您并不关心整个页面的加载,只关心某个部分。
我还编写了另一个函数,它是 GetElementByClassAndText ,它与元素上的隐式等待相同,除了它还会检查包含的文本以及允许更详细地说明您想要的内容:
public static void waitAndClick( WebDriver driver, By by, String text ) {
WebDriverWait wait = new WebDriverWait( driver, 10000 );
Function<WebDriver, Boolean> waitForElement = new waitForElement( by );
wait.until( waitForElement );
for( WebElement e : driver.findElements( by ) ) {
if( e.getText().equals( text ) ) {
Actions builder = new Actions( driver );
builder.click( e ).perform();
return;
}
}
}
以及它使用的相应函数:
public class waitForElement implements Function<WebDriver, Boolean> {
private final By by;
private String text = null;
public waitForElement( By by ) {
this.by = by;
}
public waitForElement( By by, String text ) {
this.by = by;
this.text = text;
}
@Override
public Boolean apply( WebDriver from ) {
if( this.text != null ) {
for( WebElement e : from.findElements( this.by ) ) {
if( e.getText().equals( this.text ) ) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
} else {
try {
from.findElement( this.by );
} catch( Exception e ) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
}
}
我知道您在 Ruby 中使用 Selenium,但希望我的一些代码(至少在概念上)是可移植的并对您有所帮助。
关于ruby - 如何等待 Selenium 中的页面重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6451760/