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条回答
Evening l夕情丶
2楼-- · 2019-01-17 19:20

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

查看更多
我只想做你的唯一
3楼-- · 2019-01-17 19:24

try calling find('//tr[2]//td[10]').node on it to get at the actual nokogiri object

查看更多
Fickle 薄情
4楼-- · 2019-01-17 19:24

If you're using the Poltergeist driver, these methods will allow you to inspect what matches:

http://www.rubydoc.info/gems/poltergeist/1.5.1/Capybara/Poltergeist/Node

For example:

page.find('[name="form-field"]').native.value == 'something'
查看更多
对你真心纯属浪费
5楼-- · 2019-01-17 19:28

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

查看更多
Juvenile、少年°
6楼-- · 2019-01-17 19:28

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']
查看更多
霸刀☆藐视天下
7楼-- · 2019-01-17 19:32

Another option is to can call #native on the element to return a Nokogiri::XML::Element and then convert that element to a string with #to_html:

find('//tr[2]//td[7]').native.to_html
查看更多
登录 后发表回答