The Code
This simple Python script uses the pYsearch library to return Yahoo! Web Search responses. Save this code to a file called yahoo_search.py and be sure to add your own unique application ID:
#!/usr/bin/python
# yahoo_search.py
# A quick Yahoo! Web Search script using Yahoo!'s
# pYsearch library availble in the Y!WS SDK
# [http://developer.yahoo.net/download/]
# Usage: python yahoo_search.py <Query>
import sys, string, codecs
# Use the pYsearch functions
from yahoo.search import webservices
# Grab the query from the command line
if sys.argv[1:]:
query = sys.argv[1]
else:
sys.exit('Usage: python yahoo_search.py <query>')
# Include your unique application ID
appID = 'insert your app ID'
# Query Yahoo!
search = webservices.create_search('web', appID)
search.language = "en"
search.results = 10
search.start = 1
search.query = query
# Parse the results
try:
results = search.parse_results()
except Exception, err:
print "Got an error: ", err
sys.exit(1)
# Tell standard output to handle utf-8 encoding
sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout)
# Start counter
count = search.start
# Print out the results
for result in results:
print "%s. %s\n%s\n%s\n\n" % (count, result.Title, result.Summary,
result.Url)
count += 1
The key to using the pYsearch library is importing the webservices module at the top of the script. From there, the script calls the create_search function, sets some parameters, and uses parse_results to get the entire Yahoo! response. And the last print command formats the response and displays it for the user.
The web search type is specified in the create_search function, but keep in mind that you could use any of Yahoo!'s search services here.