Ruby Watir获取页面的特定html元素

时间:2015-02-17 06:11:38

标签: ruby watir watir-webdriver

我已经尝试过这个:

puts browser.text

它有效。我想问一下是否可以只显示或打印特定元素或html标签。 例如这一个:

<button class="btn btn-add" data-role="add">Add New User</button>

有没有办法只获得这个元素?不是整个页面源。  我也试试

puts @browser.button(:class => "btn btn-add").html

,错误是:

1) Error:
test_login(TC_Login):
Selenium::WebDriver::Error::JavascriptError: invalid 'in' operand a
    [remote server] http://sample.org/user/ line 68 > Function:18:in `G'
    [remote server] http://sample.org/user/ line 68 > Function:18:in `anonymous/</<'
    [remote server] http://sample.org/user/ line 68 > Function:15:in `anonymous/<'
    [remote server] http://sample.org/user/ line 68 > Function:15:in `anonymous'
    [remote server] http://sample.org/user/:68:in `handleEvaluateEvent'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/response.rb:52:in `assert_ok'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/response.rb:15:in `initialize'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/http/common.rb:59:in `new'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/http/common.rb:59:in `create_response'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/http/default.rb:66:in `request'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/bridge.rb:640:in `raw_execute'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/bridge.rb:618:in `execute'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/remote/bridge.rb:339:in `executeScript'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.44.0/lib/selenium/webdriver/common/driver.rb:193:in `execute_script'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/atoms.rb:20:in `execute_atom'
    c:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.11/lib/watir-webdriver/elements/element.rb:290:in `outer_html'
    excel.rb:277:in `test_login'

4 个答案:

答案 0 :(得分:3)

我不知道为什么Andrew Leaf的答案对你不起作用,这是一种简单而正确的方法,你应该发布一个错误吗? 但你也可以试试这个:

browser.execute_script('return document.getElementsByClassName("btn-add")[0];').html

答案 1 :(得分:2)

@browser.button(:class => "btn btn-add").html

那应该显示元素的HTML。

答案 2 :(得分:0)

browser.button(:class => "btn btn-add")

答案 3 :(得分:0)

页面上元素的基础HTML代码可以使用方法inner_html

显示

put browser.button(:class =&gt;“btn btn-add”)。inner_html