Class: RulethuStockExchange::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/rulethu_stock_exchange/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table) ⇒ Parser

Returns a new instance of Parser.



8
9
10
# File 'lib/rulethu_stock_exchange/parser.rb', line 8

def initialize(table)
  @table = table
end

Instance Attribute Details

#tableObject (readonly)

Returns the value of attribute table.



6
7
8
# File 'lib/rulethu_stock_exchange/parser.rb', line 6

def table
  @table
end

Instance Method Details

#parseObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rulethu_stock_exchange/parser.rb', line 45

def parse
  header_data = []
  begin
    thead = table.find_element(:tag_name, "thead")
    cells = thead.find_element(:tag_name, "tr").find_elements(:tag_name, "th")
    puts "Writing header data"
    cells.each do |cell|
      header_data << cell.text
      print "."
    end
  rescue Selenium::WebDriver::Error::NoSuchElement => e
    # Handle missing header gracefully (e.g., log the error)
  end
  tbody = table.find_element(:tag_name, "tbody")
  rows = tbody.find_elements(:tag_name, "tr")
  body_data = []
  puts "\nWriting body data"
  rows.each do |row|
    data = {}
    cells = row.find_elements(:tag_name, "td")
    if header_data.empty?
      header_data = cells.map(&:text)
    end
    cells.each_with_index do |cell, index|
      data[header_data[index]] = cell.text unless header_data[index].strip.empty?
    end
    body_data << data
    print "."
  end
  body_data
end

#parse_zseObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rulethu_stock_exchange/parser.rb', line 12

def parse_zse
  tbody = table.find_element(:tag_name, "tbody")
  rows = tbody.find_elements(:tag_name, "tr")
  data_rows = []
  rows.each do |row|
    text = row.find_elements(:tag_name, "td").first.text.strip
    unless text&.upcase == "EQUITIES"
      data_rows << row unless text.empty?
    end
  end

  header_data = []
  data_rows.first.find_elements(:tag_name, "td").each do |td|
    text = td.text.strip.gsub("\n", " ") || "#"
    text = "#" if text.empty?
    header_data << text
  end

  data_rows = data_rows.slice(1, data_rows.length)

  data = []
  data_rows.each do |row|
    row_data = {}
    cells = row.find_elements :tag_name, "td"
    cells.each_with_index do |cell, index|
      key = header_data[index] || "#"
      row_data[key] = cell.text.strip
    end
    data << row_data
  end
  data
end