0

我想在 scala 中使用 fluent wait with selenium。但是我无法将以下代码转换为 Scala。请帮帮我。

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
        .withTimeout(30, SECONDS)
        .pollingEvery(5, SECONDS)
        .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() 
{
  public WebElement apply(WebDriver driver) {
  return driver.findElement(By.id("foo"));
}
});

当我在 Scala 中使用它时,我得到

@BrianMcCutchon - 嗨。当我在 Scala 中使用此代码时,它会转换为以下内容,

val wait = new FluentWait[WebDriver](driver).withTimeout(30, SECONDS).pollingEvery(5, SECONDS).ignoring(classOf[Nothing])

  val foo = wait.until(new Nothing() {
    def apply(driver: WebDriver): WebElement = driver.findElement(By.id("foo"))
  })

在此代码中,val wait 未解决。此外,没有什么似乎毫无意义

4

3 回答 3

1

此代码应使用 Java(8 及更高版本)和 Scala(2.12 以与 Java 接口互操作)中的 lambdas 编写,Function除非您有特定的理由不这样做。

爪哇:

WebElement foo = wait.until(driver -> driver.findElement(By.id("foo")));

斯卡拉:

val foo = wait.until(_.findElement(By.id("foo")))

或者

val foo = wait.until(driver => driver.findElement(By.id("foo")))

另外,wait应该有ignoring(classOf[NoSuchElementException]),没有Nothing

于 2019-01-21T08:12:49.940 回答
0

这是转换:

转换“等待”

Java 和 Scala 在这里非常相似。请注意:

  1. Scala 使用[]泛型而不是 Java 的<>.
  2. Scala 的版本SomeClass.classclassOf[SomeClass].

爪哇:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class);

斯卡拉:

val wait = new FluentWait[WebDriver](driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(classOf[NoSuchElementException])

转换“富”

这是说明函数式 Java 和 Scala 之间相似性的好地方 我正在将您的示例翻译成 Java 中的函数式并使用var它是在 Java 10 中引入的。Scala 版本与这种风格非常非常相似。

你的Java:

WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
  public WebElement apply(WebDriver driver) {
    return driver.findElement(By.id("foo"));
  }
});

带有本地类型推断的函数式 Java (JDK 10+):

var foo = wait.until(driver -> driver.findElement(By.id("foo")));

斯卡拉:

val foo = wait.until(driver => driver.findElement(By.id("foo")))

在 Scala_中,可以在函数调用中使用显式参数名称来代替。这是一种风格选择,但您也可以将上述 Scala 代码编写为:

val foo = wait.until(_.findElement(By.id("foo")))
于 2019-01-21T17:37:51.300 回答
0

我不是在这里谈论 Selenium 的 FluentWait。对于 Java 中的通用 fluent api,它应该有一个默认值,不是吗?在这种情况下,Scala 中的命名参数对我来说看起来更好。例如,

new FluentWait(timeout = 30.seconds, polling = 5.seconds)

ignoring参数被忽略,并将获得默认值classOf[NoSuchElementException]

于 2019-01-21T11:58:29.793 回答