How do I get the HTML in an element using Capybara

2019-01-17 19:00发布

I’m writing a cucumber test where I want to get the HTML in an element.

For example:

within 'table' do
  # this works
  find('//tr[2]//td[7]').text.should == "these are the comments" 

  # I want something like this (there is no "html" method)
  find('//tr[2]//td[7]').html.should == "these are the <b>comments</b>" 
end

Anyone know how to do this?

11条回答
仙女界的扛把子
2楼-- · 2019-01-17 19:34

Looks like you can do (node).native.inner_html to get the HTML content, for example with HTML like this:

<div><strong>Some</strong> HTML</div>

You could do the following:

find('div').native.inner_html
=> '<strong>Some</strong> HTML'
查看更多
Melony?
3楼-- · 2019-01-17 19:37

Most of the other answers work only in Racktest (as they use Racktest-specific features).

If your driver supports javascript evaluation (like Selenium) you can use innerHTML :

html = page.evaluate_script("document.getElementById('my_id').innerHTML")
查看更多
不美不萌又怎样
4楼-- · 2019-01-17 19:38

Well, Capybara uses Nokogiri to parse, so this page might be appropriate:

http://nokogiri.org/Nokogiri/XML/Node.html

I believe content is the method you are looking for.

查看更多
冷血范
5楼-- · 2019-01-17 19:38

You could also switch to capybara-ui and do the following:

# define your widget, in this case in your role
class User < Capybara::UI::Role
  widget :seventh_cell, [:xpath, '//tr[2]//td[7]']
end

# then in your tests
role = User.new

expect(role.widget(:seventh_cell).html).to eq(<h1>My html</h1>)
查看更多
神经病院院长
6楼-- · 2019-01-17 19:39

In my environment, find returns a Capybara::Element - that responds to the :native method as Eric Hu mentioned above, which returns a Selenium::WebDriver::Element (for me). Then :text gets the contents, so it could be as simple as:

results = find(:xpath, "//td[@id='#{cell_id}']")
contents = results.native.text

if you're looking for the contents of a table cell. There's no content, inner_html, inner_text, or node methods on a Capybara::Element. Assuming people aren't just making things up, perhaps you get something different back from find depending on what else you have loaded with Capybara.

查看更多
登录 后发表回答