How to get HTML of an element when using Poltergeist?
Asked Answered
F

3

17

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

Freeboard answered 13/11, 2013 at 12:2 Comment(0)
L
10

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']
Logrolling answered 21/1, 2016 at 21:24 Comment(1)
This is the correct answer to the question! thank youSchaaf
D
2

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.

Dis answered 24/1, 2014 at 20:58 Comment(1)
Unfortunately, this isn't enough for me. When I'm working with Poltergeist's nodes, I usually tend to go deeper in the HTML hierarchy, and it would take me too much time to figure out how to write a CSS selector for a specific node. I don't find Poltergeist irritating, nor should you :)Freeboard
W
-1

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

Wickiup answered 25/1, 2014 at 8:35 Comment(1)
I wasn't asking for the text, I was asking for the actual HTML.Freeboard

© 2022 - 2024 — McMap. All rights reserved.