Class: BaiduResult

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

Instance Method Summary collapse

Constructor Details

#initialize(page) ⇒ BaiduResult

Returns a new instance of BaiduResult.



103
104
105
106
# File 'lib/baidu.rb', line 103

def initialize(page)
    raise ArgumentError 'should be Mechanize::Page' unless page.class == Mechanize::Page
    @page = page
end

Instance Method Details

#how_manyObject



127
128
129
# File 'lib/baidu.rb', line 127

def how_many
    @how_many ||= @page.search("//span[@class='nums']").map{|num|num.content.gsub(/\D/,'').to_i unless num.nil?}.first
end

#nextObject



135
136
137
# File 'lib/baidu.rb', line 135

def next
    @page = BaiduResult.new(Mechanize.new.click(@page.link_with(:text=>/下一页/))) unless @page.link_with(:text=>/下一页/).nil?
end

#rank(host) ⇒ Object

look up a word and get the rank of a uri with $host



118
119
120
121
122
123
124
125
# File 'lib/baidu.rb', line 118

def rank(host)#on base of ranks
    ranks.each_with_index do |uri,index|
        next if uri.nil?
        return index+1 if uri.split('/')[0].strip == host
        #return index+1 if URI.parse(URI.encode(uri)).host == host
    end
    return nil
end

#ranks(host = nil) ⇒ Object



108
109
110
111
112
113
114
115
# File 'lib/baidu.rb', line 108

def ranks(host=nil)
    @ranks ||= @page.search("//table[@class=\"result\"]").map{|table|@page.search("//table[@id=\"#{table['id']}\"]//span[@class=\"g\"]").first}.map{|rank|URI('http://'+rank.text.strip.split(/\s/).first).host unless rank.nil?}
    if host.nil?
        @ranks
    else
        @ranks.each_with_index.map{|h,i| i if !h.nil? and h==host}.compact
    end
end


131
132
133
# File 'lib/baidu.rb', line 131

def related_keywords
    @related_keywords ||= @page.search("//div[@id=\"rs\"]//tr//a").map{|keyword| keyword.text}
end