Module: DuckDuckGo

Defined in:
lib/duckduckgo/search.rb,
lib/duckduckgo/result.rb,
lib/duckduckgo/version.rb

Overview

The DuckDuckGo module.

Defined Under Namespace

Classes: SearchResult

Constant Summary collapse

RESOURCE_URL =

The suffix for the URL that we visit when querying DuckDuckGo.

'https://duckduckgo.com/html/?q='
VERSION =
'0.1.5'

Class Method Summary collapse

Class Method Details

.search(hash) ⇒ Object

Searches DuckDuckGo for the given query string. This function returns an array of SearchResults.

Parameters:

  • hash (Hash)

    a hash containing the query string and possibly other configuration settings.

Raises:

  • (Exception)

    if there is an error scraping DuckDuckGo for the search results.



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
48
49
50
51
52
53
54
55
# File 'lib/duckduckgo/search.rb', line 19

def self.search(hash)

  results = []

  raise 'Hash does not contain a query string.' if hash[:query].nil?
  html = open("#{RESOURCE_URL}#{CGI::escape(hash[:query])}")

  document = Nokogiri::HTML(html)

  document.css('#links').each do |result|
    title_element = result.css('.result__a').first
    raise 'Could not find result link element!' if title_element.nil?

    title = title_element.text
    raise 'Could not find result title!' if title.nil?

    uri = title_element['href']
    raise 'Could not find result URL!' if uri.nil?

    # Attempt to follow redirects, since DuckDuckGo often aggregates search results from Yahoo.
    begin
      final_uri = open(uri, :allow_redirections => :all).base_uri.to_s
    rescue
      final_uri = uri
    end

    description_element = result.css('.result__snippet').first
    raise 'Could not find result description element!' if description_element.nil?

    description = description_element.text
    raise 'Could not find result description!' if description.nil?

    results << SearchResult.new(final_uri, title, description)
  end

  return results
end