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

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

问题描述

我正在尝试从隐藏的 <div> 中读取示例字符串 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";

在火狐中.

这也是.

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天全站免登陆