Google Suggest Grabber

Krstevski 0 Tallied Votes 648 Views Share

The class GoogleSuggest will help you to grab the Google suggestion(s) for given expression.

Note: The urllib2 module has been split across several modules in Python 3.0 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

Example and output:

>>> ================================ RESTART ================================
>>>
>>> suggestions = GoogleSuggest("daniweb").read()
>>> for suggest in suggestions:
print suggest


daniweb
daniweb llc
daniweb wiki
daniweb popup
daniweb c++
daniweb forum
daniweb java
daniweb login
daniweb php
daniweb python
>>> suggestion = GoogleSuggest().read("google")
>>> for suggest in suggestion:
print suggest


google maps
google.com
google earth
google translate
google voice
google images
google docs
google scholar
google chrome
google books
>>>

#!/usr/bin/python
# -*- coding: utf-8 -*-

##################################################
#       Google Suggest Grabber
#-------------------------------------------------
#   Copyright:    (c) 2010 by Damjan Krstevski.
#   License:      GNU General Public License v3
#   Feedback:     krstevsky[at]gmail[dot]com
##################################################

"""
GoogleSuggest
This module will help you to grab the Google suggestion for some expression

Usage:
    # Create instance without given value
    GoogleSuggest()
    # Create instance with given value
    GoogleSuggest( expression )
    # Grab the suggestion
    GoogleSuggest( expression ).read()
    GoogleSuggest().read( expression )
    Instance.read()
    Instance.suggest
    Instance.read( expression )

    # The method read( expression = None )
    # sets the list with the suggestion(s) and
    # returns the list with the suggestion(s)
"""

# public symbols
__all__ = ["url", "tag", "attribute", "q", "suggest", "read"]

__version__     = "1.0.0"


from urllib2 import urlopen
from xml.dom.minidom import parseString


# @Class GoogleSuggestException(Exception)
class GoogleSuggestException(Exception):
    """ Handling GoogleSuggest exception(s) """
    pass
# @End of: GoogleSuggestException(Exception)


# @Class GoogleSuggest(object)
class GoogleSuggest(object):
    """ Class GoogleSuggest - Google suggestion grabber """
    def __init__( self, word = None, tag = "suggestion", attr = "data" ):
        self.url        = "http://google.com/complete/search?output=toolbar&q="
        self.tag        = tag
        self.attribute  = attr
        self.q          = word
        self.suggest    = []


    # Destructor
    def __del__( self ):
        """ Destroy (Liberate) the used memory """
        self.suggest = None

        
    # Filling the list of the suggestion(s)
    def __fill( self, data = None ):
        """ Fill the suggestion(s) """
        if not data:
            return

        try:
            self.suggest = []
            doc = parseString( data )
            nodes = doc.getElementsByTagName( self.tag )
        
            for node in nodes:
                tmp = node.getAttribute( self.attribute )
                self.suggest.append( tmp )
        except Exception as ex:
            raise GoogleSuggestException( ex )


    # Unsolved ...
    def __filter( self, text ):
        """ Filtering the bad character(s) from the query string """
        return text


    #Reading the Google suggestion(s)
    def read( self, word = None ):
        """ Read the suggestion(s) """
        query = None
        if word:
            query = word
        else:
            query = self.q
        if not query:
            return

        try:
            data = urlopen( self.__filter( self.url + query.replace(" ", "+") ) ).read()
            self.__fill( data )
            return self.suggest
        except Exception as ex:
            raise GoogleSuggestException( ex )
# @End of: GoogleSuggest(object)
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Can not say I understood much, especially for reason of doing all this stuff, but here is what I cathered from program that I understood. For others like me.

import urllib2
from xml.dom.minidom import parse

def google_suggest(word):
    """Google Suggest function google_suggest(word)
    returns list of unicode strings of suggestions"""
    page = parse(urllib2.urlopen(
        "http://google.com/complete/search?output=toolbar&q=" + 
        word.replace(" ","+")))
    return [node.getAttribute('data')
            for node in page.getElementsByTagName('suggestion')]

if __name__ == '__main__':
    print '\n'.join(google_suggest('DaniWeb'))
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Here is one interesting library on using Google Search:
http://www.catonmat.net/blog/python-library-for-google-search/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.