You get always the same output because you ask always the results for Mocha
. The same happens when you put the same word in the Google search bar
If you want to have different outputs you have to change the query that you perform. My approach would be to rely on a random word generator so to change the search every time you run the code
Here I modified your own snippet to perform this exact job:
from googleapiclient.discovery import build
import pprint
import requests
import random
my_api_key = 'AIzaSyDouxn16TxJ8vym5AC1_A3nlMCzc5gpRjg'
my_cse_id = '007260579175343269764:pt3gyxmajmg'
def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, searchType="image", **kwargs).execute()
return res['items']
def random_query():
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = requests.get(word_site)
WORDS = response.content.splitlines()
# print(WORDS)
number = random.randint(0, len(WORDS));
# print(number)
word = WORDS[random.randint(0, len(WORDS))].decode()
# print(word)
return word
def main():
results = google_search(
random_query(), my_api_key, my_cse_id)
pprint.pprint(results)
if __name__ == "__main__":
main()
Edit after clarification in the comment
In order to have different results for the same query you can pick the results from a page other than the first. The approach followed comes from this answer, you can tweak the start index as you prefer. In this snippet we select the page choosing a random number between 1 and 100. Keep in mind that every 10 units you have the next page, so as per the link given before "Second page has URL which contains start=10 parameter. Third page has URL which contains start=20", etc
from googleapiclient.discovery import build
import pprint
import requests
import random
my_api_key = 'AIzaSyDouxn16TxJ8vym5AC1_A3nlMCzc5gpRjg'
my_cse_id = '007260579175343269764:pt3gyxmajmg'
def google_search(search_term, api_key, cse_id, start, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, searchType="image", **kwargs, start=start).execute()
return res['items']
def random_start():
number = random.randint(1,101)
print(number)
return number
def main():
start_index = random_start()
results = google_search(
'Mocha', my_api_key, my_cse_id, start_index)
pprint.pprint(results)
if __name__ == "__main__":
main()