如何使用Watir(Ruby)从非可见元素中读取文本?

Jer*_*emy 5 ruby watir watir-webdriver

页面上有一个div不可见,但有一些我想要捕获的值.在它上面调用文本会返回一个空字符串.

如何在不处理原始html的情况下显示值?无论浏览器中文本的可见性如何,我都可以强制.text返回实际值吗?

irb(main):1341:0> d.first.visible?
=> false

irb(main):1344:0> d.first.html
=> "<div class=\"day\">7</div>"

irb(main):1345:0> d.first.text
=> ""
Run Code Online (Sandbox Code Playgroud)

PS:有很多div(页面缓存响应并相应地显示它们).我考虑更改所有显示:在页面中没有或点击使它们可见但我希望尽可能避免这种情况.如果不可能,改变所有显示器的解决方案都不是首选的解决方法.

PPS:诅咒,我试图超载可见?Watir :: Element类中的方法总是返回true,但是没有做到这一点.

irb(main):1502:0> d.first.visible?
=> true

irb(main):1504:0> d.first.text
=> ""
Run Code Online (Sandbox Code Playgroud)

Jus*_* Ko 7

我认为你必须使用javascript来获得这个.

e = d.first
browser.execute_script('return arguments[0].textContent', e)
#=> "7"
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于类似Mozilla的浏览器.对于类似IE的浏览器,您需要使用innerText.虽然如果你使用的是watir-classic,那就简单了d.first.innerText(即没有execute_script必要).

使用attribute_value:

事实证明,使用该attribute_value方法可以使其更简单.似乎它可以获得与javascript相同的属性值.

d.first.attribute_value('textContent')
#=> "7"
Run Code Online (Sandbox Code Playgroud)

使用inner_html

如果元素只包含文本节点(即没有元素),您还可以使用inner_html:

d.first.inner_html
#=> "7"
Run Code Online (Sandbox Code Playgroud)