Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the HTML in an element using Capybara?

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?

like image 514
Jon Kruger Avatar asked Nov 01 '10 18:11

Jon Kruger


5 Answers

You can call HTML DOM innerHTML Property:

find('//tr[2]//td[7]')['innerHTML']

Should work for any browser or driver. You can check all available properties on w3schools

like image 95
llighterr Avatar answered Nov 09 '22 12:11

llighterr


This post is old, but I think I found a way if you still need this.

To access the Nokogiri node from the Capybara element (using Capybara 1.0.0beta1, Nokogiri 1.4.4) try this:

elem = find('//tr[2]//td[10]')
node = elem.native
#This will give you a Nokogiri XML element

node.children[1].attributes["href"].value.should == "these are the <b>comments</b>"

The last part may vary for you, but you should be able to find the HTML somewhere in that node variable

like image 36
Eric Hu Avatar answered Nov 09 '22 11:11

Eric Hu


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.

like image 20
Steve Avatar answered Nov 09 '22 12:11

Steve


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'
like image 12
Tobias Cohen Avatar answered Nov 09 '22 11:11

Tobias Cohen


I ran into the same issue as Cyril Duchon-Doris, and per https://github.com/teampoltergeist/poltergeist/issues/629 the way to access the HTML of an Capybara::Poltergeist::Node is via the outerHTML property, e.g.:

find('//tr[2]//td[7]')['outerHTML']
like image 7
Geoff The Avatar answered Nov 09 '22 11:11

Geoff The