Selenium Webdriver -点击隐藏元素

lrpiutwd  于 2023-06-23  发布在  其他
关注(0)|答案(5)|浏览(133)

我正在尝试在Google Drive中自动上传文件功能。
用于传递参数的元素用height -0 px隐藏。
任何用户操作都不会使此元素可见。因此,我需要一个解决办法,点击元素,而它是不可见的。

<input type="file" style="height: 0px; visibility: hidden; position: absolute; width: 340px; font-size: inherit;" multiple=""/>

上面元素的xpath是-

//*[@class='goog-menu goog-menu-vertical uploadmenu density-tiny']/input

我在用

WebDriver.findElement(By.xpath(<xpath>).sendKeys(<uploadFile>)

例外情况-

org.openqa.selenium.ElementNotVisibleException
  • 元素当前不可见,因此不能与之交互。

我试过使用JavascriptExecutor。但找不到确切的语法。

093gszye

093gszye1#

试试这个:

WebElement elem = yourWebDriverInstance.findElement(By.xpath("//*[@class='goog-menu goog-menu-vertical uploadmenu density-tiny']/input"));
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";

((JavascriptExecutor) yourWebDriverInstance).executeScript(js, elem);

上面的一堆会改变你的文件输入控件的可见性。然后,您可以继续执行文件上传的常规步骤,如:

elem.sendKeys("<LOCAL FILE PATH>");

请注意,通过更改输入字段的可见性,您正在干预测试中的应用程序。注入脚本来改变行为是侵入性的,不建议在测试中使用。

ekqde3dh

ekqde3dh2#

简单的解决方案:

WebElement tmpElement = driver.finElement(ElementLocator);
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", tmpElement);
r3i60tvu

r3i60tvu3#

试试这个示例代码:

JavascriptExecutor executor= (JavascriptExecutor)driver;
executor.executeScript("document.getElementById('ID').style.display='block';");
Select select = new Select(driver.findElement(By.id("ID")));
select.selectByVisibleText("value");
Thread.sleep(6000);

通过使用JavaScript执行器,并使元素可见,然后通过ID单击元素。希望能帮到你。

s2j5cfk0

s2j5cfk04#

试试这个:

WebElement elem = yourWebDriverInstance.findElement(
   By.cssSelector(".uploadmenu > input"));
String js = 
  "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
((JavascriptExecutor) yourWebDriverInstance).executeScript(js, elem);

这里我用CSS选择器替换了XPath。让我知道上面的脚本是否有效。

3lxsmp7m

3lxsmp7m5#

您可以给予以下操作:

((JavascriptExecutor)driver).executeScript("$('.goog-menu.uploadmenu > input').click();");

相关问题