【发布时间】:2021-08-15 01:24:51
【问题描述】:
我有一个用 Java 编写的 Selenium 代码,我需要找到明显可见的元素,如屏幕截图所示。 html代码来自谷歌登录API页面。
代码如下:
if(BaseSteps.elementExists(By.xpath("//*[@role=\"button\"]"), 30))
{
System.out.println($(By.xpath("//*[@role=\"button\"]")));
$(By.xpath("//*[@role=\"button\"]")).shouldBe(visible, ofSeconds(120)).click();
}
在开发者工具中可以看到图片上的按钮有display:inline-block。 println() 调用写入
<div aria-disabled="false" class="U26fgb O0WRkf oG5Srb C0oVfc kHssdc M9Bg4d" data-custom-id="iPWQ6" data-id="ssJRIf" jsaction="click:cOuCgd; mousedown:UX7yZ; mouseup:lbsD7e; mouseenter:tfO1Yc; mouseleave:JywGue; focus:AHmuwe; blur:O22p3e; contextmenu:mg9Pef;touchstart:p6p2H; touchmove:FwuNnf; touchend:yfqBxc(preventMouseEvents=true|preventDefault=true); touchcancel:JMtRjd;" jscontroller="VXdfxd" jsname="LgbsSe" jsshadow role="button" tabindex="0" displayed:false></div>
最后是“显示:假”。我不明白这是什么意思。谁能告诉我问题出在哪里?
【问题讨论】:
-
你有什么错误吗?
-
在那个 web 元素上尝试 isDisplay() 看看它是返回 false 还是 true。
-
您在浏览器中看到的元素似乎是由 JavaScript 创建并直接添加到 DOM 中的。如果您使用的是基于 Selenium 文本的驱动程序,则它无法看到这些元素,因为它们只存在于浏览器的内存中,而不存在于 HTML 文件中。如果是这种情况,您必须使用直接与浏览器交互的驱动程序。
-
@whbogado 你能更具体一点吗?它是一个 Chrome 驱动程序。我第一次听说 Javascript 创建的元素对 Selenium 不可见。我有另一个测试,它适用于由 Javascript 创建的元素并且它有效。有相关文档吗?
-
有 2 个相同的元素,因为属性
role并不总是唯一的。你不能假设它会。正如@pcalkins 所说,最好针对id而不是role