如何使用Selenium WebDriver从隐藏元素中读取文本? [英] How to read text from hidden element with Selenium WebDriver?

查看:994
本文介绍了如何使用Selenium WebDriver从隐藏元素中读取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从隐藏的< div> 中读取示例String 1000 ,如下所示:

I'm trying to read the example String 1000 out of a hidden <div> like this:

<div id="hidden_div" style="visibility:hidden">1000</div>

我知道 WebElement.getText()不适用于Selenium 2(WebDriver)中的隐藏元素,因此我搜索了解决方案(喜欢这个)并且显然以下代码应该有效:

I am aware that WebElement.getText() does not work on hidden elements in Selenium 2 (WebDriver), so I searched for solutions (like this one) and apparently the following code should work:

WebElement hiddenDiv = seleniumDriver.findElement(By.id("hidden_div"));
String n = hiddenDiv.getText(); // does not work (returns "" as expected)
String script = "return arguments[0].innerText";
n = (String) ((JavascriptExecutor) driver).executeScript(script, hiddenDiv);

但它对我不起作用,变量 n 总是以 null 结尾。我做错了什么?

But it doesn't work for me, the variable n always ends up as null. What am I doing wrong?

推荐答案

编辑:哦,这样可行。

String script = "return document.getElementById('hidden_div').innerHTML";

在Firefox中。

同样如此这个。

String script = "return arguments[0].innerHTML";

我也尝试了但它似乎不适用于纯Javascript。使用
Jquery启动浏览器,如此处所述。 如何在Selenium中使用JQuery?并使用以下代码编写脚本。

I tried as well but it does not seem to work with pure Javascript. Start the browser with Jquery as mentioned here. How to use JQuery in Selenium? and use following code for script.

String script = "return $('#hidden_div').text();";

这样做。

这篇关于如何使用Selenium WebDriver从隐藏元素中读取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆