Skip to content

Instantly share code, notes, and snippets.

@dolisy
Created July 18, 2017 16:40
Show Gist options
  • Save dolisy/3e2d7a3333150181e23a0322b0c90190 to your computer and use it in GitHub Desktop.
Save dolisy/3e2d7a3333150181e23a0322b0c90190 to your computer and use it in GitHub Desktop.
Displays all articles available on Courrier International by title, and asks the user to select one. The selected article will be presented to the user to be read.
require "open-uri"
require "nokogiri"
def articles(link)
result = []
articles = []
doc = Nokogiri::HTML(open(link))
nodeset = doc.css('a')
articles = nodeset.map { |element| element["href"] }.compact
articles.each do |article|
begin
array = []
doc = Nokogiri::HTML(open("http://www.courrierinternational.com#{article}"))
doc.search(".article-title").each_with_index do |element, index|
array << "#{element.text.strip}"
end
doc.search(".article-text").each_with_index do |element, index|
array << "#{element.text.strip}"
end
result << { title: array[0], text: array[1] }
rescue
next
end
end
return result
end
def articles_list(link)
articles_list = []
articles_array = articles(link)
articles_array.each do |info|
articles_list << info[:title]
end
return articles_list
end
def get_article(link)
puts "Select an article title in the list below:"
puts articles_list(link)
puts "Now enter the article title you would like to read:"
user_choice = gets.chomp
articles_array = articles(link)
articles_hash = {}
articles_array.each do |element|
articles_hash[element[:title]] = element[:text]
end
return articles_hash[user_choice]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment