Created
October 18, 2023 11:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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