Skip to content

Instantly share code, notes, and snippets.

@rishey
Created August 14, 2013 19:34
Show Gist options
  • Save rishey/6234714 to your computer and use it in GitHub Desktop.
Save rishey/6234714 to your computer and use it in GitHub Desktop.
# Solution for Challenge: Scraping HN 1: Building Objects. Started 2013-08-14T15:21:45+00:00
require 'open-uri'
require 'nokogiri'
html_file = open(ARGV.join)
doc = Nokogiri::HTML(html_file)
ARGV_POST = {:title => doc.search('.title > a:first-child').map {|link| link.inner_text},
:url => doc.search('.title > a:first-child').map {|link| link['href']},
:points => doc.search('.subtext > span:first-child').map { |span| span.inner_text},
:item_id => doc.search('.subtext > a:nth-child(3)').map {|link| link['href']},
:comment_text => doc.search('.comment > font:first-child').map { |font| font.inner_text}}
class Post
attr_reader :title, :url, :points, :item_id
attr_accessor :comment_text, :comment
def initialize(args)
@title = args [:title]
@url = args [:url]
@points = args [:points]
@item_id = args [:item_id]
@comment_text = args [:comment_text]
@comment = []
end
def parse
@comment_text.each do |comment|
@comment.push Comment.new(comment)
end
end
def show_last_comment
@comment_text.last
end
def add_comment(args)
@comment_text << Comment.new(args).comment_text
@comment << Comment.new(args)
end
def to_s
puts "Title: #{@title.join}"
puts "\# comments: #{@comment.length}"
puts "Last Comment: #{self.show_last_comment}"
end
end
class Comment
attr_accessor :comment_text
def initialize(comment_text)
@comment_text = comment_text
end
end
mypost = Post.new(ARGV_POST)
mypost.parse
p mypost.to_s
# mypost = Post.new("title","http://url",123,131)
# p mypost.title == "title"
# mypost.add_comment("This is my comment")
# p mypost.comment[0].comment_text == "This is my comment"
# mypost.add_comment"This is my second comment"
# p mypost.comment[1].comment_text
# html_file = open('post.html')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment