Janko
Janko

Reputation: 9305

How to get HTML of an element when using Poltergeist?

I'm using Capybara with the Poltergeist driver. My question is: how to get the HTML (string) of a node?

I've read that using the RackTest driver you can get it like this:

find("table").native         #=> native Nokogiri element
find("table").native.to_html #=> "..."

But with Poltergeist calling #native on a node returns a Capybara::Poltergeist::Node, not a native Nokogiri element. And then calling #native again on the Capybara::Poltergeist::Node returns the same Capybara::Poltergeist::Node again (that is, it returns self).

It has become slightly irritating having to look at the HTML from the entire page to find what I'm looking for :P

Upvotes: 17

Views: 2313

Answers (3)

superuseroi
superuseroi

Reputation: 1348

I am adding this answer for others who land here. The solution is dead simple.

following the example you provided it would be:

find("table")['outerHTML']

Upvotes: 10

Avinash Agrawal
Avinash Agrawal

Reputation: 1138

Its can be done like this

lets say on google.co.in you wana fetch INDIA

enter image description here

on step.rb file under your function write this line

x =  page.find(:xpath,'//*[@id="hplogo"]/div' , :visible => false).text
puts x  

x will display "India"

Terminal o/p

enter image description here

Upvotes: -1

jstaab
jstaab

Reputation: 3855

I also find Poltergeist irritating. Here's what I did:

def nokogiri(selector)
    nokogiri = Nokogiri::HTML(page.html);
    return nokogiri.css(selector)[0]
end

This takes a css selector, and returns a native nokogiri element, rather than poltergeist's idiocy. You'll also have to require 'nokogiri', but it shouldn't be a problem since it's a dependency for poltergeist.

Upvotes: 2

Related Questions