通过Selenium中的Java交互API移至不透明度0的WebElement

请考虑来自internal Selenium test page的以下<select>

<select id="invisi_select" style="opacity:0;">
    <option selected value="apples">Apples</option>
    <option value="oranges">Oranges</option>
</select>

它用于模拟id建议的不可见元素,方法是将opacity设置为0。

尽管该元素不可见,但用户实际上可以与其交互。如果我在浏览器中打开页面并单击元素的位置,则会打开选择菜单。我相信这也是WebElement#isDisplayed()返回此元素true的原因,这也是这些旧的Selenium问题所建议的:

要执行诸如点击之类的操作,我们出于多种原因最近切换到了Java interactions API,例如,切换到了prevent ElementClickInterceptedExceptions。 (请注意,这并不是重构一堆Selenium测试,这是在Selenium API之上运行的通用操作执行程序的背景下发生的。)但是,如果我执行以下操作:

WebElement applesOption = /* get apples option */
new actions(webDriver).moveToElement(applesOption)
        .click()
        .perform();

移动到元素会引发以下异常:

org.openqa.selenium.JavascriptException: javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite.

我猜这是因为elementsFromPoint()通过WebDriver Actions API似乎为这样的透明元素返回了“非有限”双精度值?

使用actions时是否可以防止这种情况发生?也许,除了检查元素是否可点击(ExpectedConditions#elementToBeclickable(...))之外,我还必须解析{听起来很恐怖的”属性,例如opacity

yegenting1 回答:通过Selenium中的Java交互API移至不透明度0的WebElement

我只是在本地尝试了示例文件,下面的代码没有例外。

WebElement e = driver.findElement(By.id("invisi_select"));
Select select = new Select(e);
select.selectByValue("apples");
System.out.println(select.getFirstSelectedOption().getText());
select.selectByValue("oranges");
System.out.println(select.getFirstSelectedOption().getText());

它打印

Apples
Oranges
,

此错误消息...

org.openqa.selenium.JavascriptException: javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite.

...表示 WebDriver 实例由于一个或其他原因而无法专注于元素:

  • 尝试与元素交互时,元素未正确加载。
  • 该元素没有引起关注。

解决方案

您可以使用Java interactions API Class 来代替Select,还可以使用以下Locator Strategies之一:

  • 使用cssSelectorselectByValue()

    Select s = new Select(driver.findElement(By.cssSelector("select#invisi_select")));
    s.selectByValue("apples");
    
  • 使用xpathselectByVisibleText()

    Select s = new Select(driver.findElement(By.xpath("//select[@id='invisi_select']")));
    s.selectByVisibleText("Apples");
    

参考文献

您可以在以下位置找到几个相关的详细讨论:

本文链接:https://www.f2er.com/3157447.html

大家都在问