Google Custom Search creates intra-Site Search
Google Custom Search allows you to create a search tailored to your needs. Google Search Ajax API is provided by default. Based on this API, you can create your own intra-site Search. However, you can only use JavaScript, and the flexibility is poor. In addition, APIs in json format are provided, which can contain two addresses.
Http://ajax.googleapis.com/ajax/services/search/web? V = 1.0 & cx = [cx] & q = [keyword]
And
Http://www.google.com/uds/GwebSearch? Cx = [cx] & key = [key] & v = 1.0 & rsz = large & q = [keyword]
I only officially introduced the former, and I used the latter.
In the GAE framework, simplejson can be used to operate json data for serialization and deserialization.
Process:
1. Declare two classes
# Save each search result
Class searchItem ():
Title = ""
Url = ""
Description = ""
# Save the entire search result
Class serachReslut ():
Items = []
Count = len (items)
Start = 0
SC = 0
Keyword = ""
Prev = False
Next = False
2. Declare the getSearch () method
Def getSearch (q, start = 0): # q indicates the keyword; start indicates the start search result.
Q = urllib. quote (q) # encode keywords
Url = searchurl. substitute (q = q, start = start) # splice the search url
Url = url. encode ('utf-8') # url Encoding
Data = urlfetch. fetch (url). content # capture search results using uflfetch
Data = simplejson. loads (data) # bind json data to data
S = serachReslut () # One serachReslut instance
If data ['responsedata'] ['results'] = []:
S. items = None # If no search result is returned, None is returned.
Else:
Results = data ['responsedata'] ['result']
S. start = start
S. keyword = urllib. unquote (q)
S. items = []
For result in results: # print the result and save the data to the s. items list.
Item = searchItem ()
Item. title = result ['title']
Item. url = result ['url']
Item. description = result ['content']
S. items. append (item)
S. SC = data ['responsedata'] ['cursor '] ['estimatedresultcount'] # obtain the number of search results
If start> = 8: # Next page, previous page processing.
S. prev = '/search /? Q = % s & s = % d' % (q, start-8)
If start <int (s. SC)-8:
S. next = '/search /? Q = % s & s = % d' % (q, start + 8)
Return s
Here, for simplicity, there is no fault tolerance, and it will be improved in the future.
3. Call
Def get (self ):
Q = self. request. get ('q'). encode ('utf-8 ')
Start = int (getinput (self,'s ', '0 '))
Template_value = {'search': getSearch (q, start), 'q': q}
Self. render ('themes/benben/search.html ', template_value)
This is a perfect intra-site search. Can the demo see the search at the top, or view the http://www.119797.com/search? Q = pineapple
Related reading:
- Ajaxsearch documentation
- The URL Fetch API
Related downloads:
- Google-search-api.py (1.8 KB)