Chet
Chet

Reputation: 144

How to extract <style> content from HTML file in Ruby?

I've copied contents from a index.html file. Now I just want to copy everything that's inside the style tags. How can I do this?

 file = File.open("filepath/index.html", "rb")
 @html_file_contents = file.read  //@html_file_contents has raw html from which I need to extract style tag contents.

Upvotes: 1

Views: 670

Answers (1)

Devstr
Devstr

Reputation: 4641

You can use Nokogiri gem

require 'nokogiri'

file = File.open("filepath/index.html", "rb")
page = Nokogiri::HTML(file.read)
first_style_tag = page.css('style')[0]
puts first_style_tag.text

see this tutorial http://ruby.bastardsbook.com/chapters/html-parsing/

Not tested, please try it out

Upvotes: 2

Related Questions