Class: BaiduResult
- Inherits:
-
SearchResult
- Object
- SearchResult
- BaiduResult
- Defined in:
- lib/baidu.rb
Instance Method Summary collapse
- #has_result? ⇒ Boolean
- #how_many ⇒ Object
-
#initialize(page) ⇒ BaiduResult
constructor
A new instance of BaiduResult.
- #next ⇒ Object
- #ranks ⇒ Object
- #related_keywords ⇒ Object
Methods inherited from SearchResult
Constructor Details
#initialize(page) ⇒ BaiduResult
Returns a new instance of BaiduResult.
310 311 312 313 |
# File 'lib/baidu.rb', line 310 def initialize(page) raise ArgumentError 'should be Mechanize::Page' unless page.class == Mechanize::Page @page = page end |
Instance Method Details
#has_result? ⇒ Boolean
361 362 363 |
# File 'lib/baidu.rb', line 361 def has_result? @page.search('//div[@class="nors"]').empty? end |
#how_many ⇒ Object
return the top rank number from @ranks with the input host def rank(host)#on base of ranks
ranks.each do |id,line|
id = id.to_i
if host.class == Regexp
return id if line['host'] =~ host
elsif host.class == String
return id if line['host'] == host
end
end
return nil
end
349 350 351 |
# File 'lib/baidu.rb', line 349 def how_many @how_many ||= @page.search("//span[@class='nums']").map{|num|num.content.gsub(/\D/,'').to_i unless num.nil?}.first end |
#next ⇒ Object
357 358 359 |
# File 'lib/baidu.rb', line 357 def next @page = BaiduResult.new(Mechanize.new.click(@page.link_with(:text=>/下一页/))) unless @page.link_with(:text=>/下一页/).nil? end |
#ranks ⇒ Object
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/baidu.rb', line 315 def ranks return @ranks unless @ranks.nil? @ranks = Hash.new @page.search("//table[@class=\"result\"]").each do |table| id = table['id'] @ranks[id] = Hash.new url = @page.search("//table[@id=\"#{table['id']}\"]//span[@class=\"g\"]").first a = @page.search("//table[@id=\"#{table['id']}\"]//h3/a") @ranks[id]['text'] = a.text @ranks[id]['href'] = a.first['href'].sub('http://www.baidu.com/link?url=','').strip unless url.nil? url = url.text.strip @ranks[id]['host'] = Addressable::URI.parse(URI.encode("http://#{url}")).host else @ranks[id]['host'] = nil end end #@page.search("//table[@class=\"result\"]").map{|table|@page.search("//table[@id=\"#{table['id']}\"]//span[@class=\"g\"]").first}.map{|rank|URI(URI.encode('http://'+rank.text.strip)).host unless rank.nil?} @ranks end |
#related_keywords ⇒ Object
353 354 355 |
# File 'lib/baidu.rb', line 353 def @related_keywords ||= @page.search("//div[@id=\"rs\"]//tr//a").map{|keyword| keyword.text} end |