forked from HenryHengZJ/flowise-streamlit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch-api
43 lines (36 loc) · 1.43 KB
/
search-api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import requests
def google_search(query, api_key, cx_id, num_results=5):
"""
A function that performs a web search using Google Custom Search API.
:param query: The search term provided by the user.
:param api_key: Your Google API key.
:param cx_id: Your custom search engine ID.
:param num_results: Number of results to return (default is 5).
:return: List of search result titles and URLs.
"""
url = 'https://www.googleapis.com/customsearch/v1'
params = {
'q': query,
'key': api_key,
'cx': cx_id,
'num': num_results
}
response = requests.get(url, params=params)
search_results = response.json()
if 'items' in search_results:
results = []
for item in search_results['items']:
title = item['title']
link = item['link']
snippet = item.get('snippet', '') # Brief summary of the search result.
results.append({'title': title, 'link': link, 'snippet': snippet})
return results
else:
return 'No results found.'
# Example usage
api_key = 'your_google_api_key' # Replace with your API Key
cx_id = 'c744c356cbc574107' # Replace with your Custom Search Engine ID
query = 'latest sports news'
search_results = google_search(query, api_key, cx_id)
for result in search_results:
print(f"Title: {result['title']}\nLink: {result['link']}\nSnippet: {result['snippet']}\n")