ITKGrades.rb

From ICO wiki
Revision as of 01:03, 1 March 2012 by Anroots (talk | contribs) (Created page with 'Tegemist on Ruby klassiga, mis tagastab http://ruby-doc.org/core-1.9.3/Hash.html Hash'i õpilase hinnetega. = Kasutus = = Kood = Vaata koodi GitHub keskkonnas: https://gis…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Tegemist on Ruby klassiga, mis tagastab [Hash]'i õpilase hinnetega.

Kasutus

Kood

Vaata koodi GitHub keskkonnas: https://gist.github.com/1944799

#!/usr/bin/env ruby

# Estonian IT College grade sheet scraper
# A dirty version for just getting the job done.
# Maybe prettify in the future.
#
# Version 1.0
# Author "Ando Roots" <anroots@itcollege.ee>
# Created 29.02.2012
# Licence Apache v2 http://www.apache.org/licenses/LICENSE-2.0.html


require "rubygems"
require "mechanize"

# Scrapes student grades from ITK ÕIS
# and returns a hash in the format
# {
# 	subject_name => {
#		grade_name => grade
#	},
# }
#
# Example usage:
# 
# ITK = ITKGrades.new("MY_USERNAME", "MY_PASSWORD", MY_STUDENT_CODE) # Instance and login
# ITK.fetch # Actually fetch and scrape the grades
# pp ITK.grades # Print out the hash of my grades
#
class ITKGrades

	@@login_url = "https://itcollege.ois.ee/et/"

	@username = nil
	@password = nil
	@student_id = nil

	@grades_url = nil

	@grades = nil

	# Accessor for grades
	def grades
		@grades
	end
	
	# Save login data
	def initialize(username, password, student_id)
		@username = username
		@password = password
		@student_id = student_id
		@grades_url = "https://itcollege.ois.ee/et/grade?student_id=" + @student_id.to_s
	end

	# Get HTML for the grades page
	def get_grades_page

		agent = Mechanize.new
		page = agent.get(@@login_url)

		login_form = page.form

		login_form.username = @username
		login_form.pw = @password

		page = agent.submit(login_form, login_form.button)

		return agent.get(@grades_url)
	end

	# Scrape grades into grades hash from the grades page
	def scrape_grades(page)
		
		@grades = {}
		grade_rows = page.search('#mainWindow table.data tr')

		grade_rows.each do |row|
			if row.at_css('th') then

				@grades[row.search('th').text] = {}
				next
			end

			paper = row.search('td:first').text.gsub(/\t/, '').gsub("-","").strip
			grade = row.search('td:last').text.gsub(/\t/, '').gsub("-","").strip
	
			if paper.empty? || grade.empty? then
				next
			end
	
			subjects = @grades.keys
			current_subject = subjects[subjects.length-1]
	
			@grades[current_subject][paper] = grade
	
		end
	end

	# Fetch grades. Call this first!
	def fetch
		scrape_grades(get_grades_page)
		return @grades
	end

end

Autor

Koodi kirjutas User:Anroots