Module: RankChecker::Google

Defined in:
lib/rank_checker.rb

Class Method Summary collapse

Class Method Details

.check(search = nil, domain = nil, search_depth = 20) ⇒ Object



11
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
44
45
46
47
# File 'lib/rank_checker.rb', line 11

def self.check(search = nil, domain = nil, search_depth = 20)
  unless search.nil? or domain.nil?
    found = false
    page = 0
    patterns = [/^.*q=(.*)&sa.*$/i, /^.*url=(.*)&sa.*$/i]

    while not found and page <= search_depth
      page += 1
      position = (page - 1) * 10

      doc = Nokogiri::HTML(open("https://www.google.com/search?q=#{CGI::escape(search)}&start=#{position}&sa=N"))

      doc.css('.r a').each do |link|
        host = ''
        position += 1
        
        patterns.each do |pattern|
          page_url = link.attributes['href'].value.match(pattern)
          if not page_url.nil?
            host = URI.parse(page_url[1]).host
            break
          end
        end

        if not host.nil? and host.gsub('www.', '') == domain.gsub('www.', '')
          found = true
          break
        end
      end

    end

    position = nil if found == false
    
    return position
  end
end