Skip to content

Instantly share code, notes, and snippets.

@thetafferboy
Created October 18, 2023 11:17
Show Gist options
  • Save thetafferboy/96ff6c27a6ed556c6f68b0d925a036aa to your computer and use it in GitHub Desktop.
Save thetafferboy/96ff6c27a6ed556c6f68b0d925a036aa to your computer and use it in GitHub Desktop.
Connect to Google CSE and get title and URL of top 10 results
import requests
def get_top_10_search_results(query, api_key, cx):
endpoint = "https://www.googleapis.com/customsearch/v1"
params = {
'q': query,
'key': api_key,
'cx': cx,
'num': 10
}
response = requests.get(endpoint, params=params)
data = response.json()
if 'items' not in data:
return []
results = []
for item in data['items']:
title = item['title']
link = item['link']
results.append((title, link))
return results
# Example usage:
# api_key = "YOUR_API_KEY"
# cx = "YOUR_CX_VALUE"
# query = "example search"
# results = get_top_10_search_results(query, api_key, cx)
# for title, link in results:
# print(title, link)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment