Advertisement
shoaib-santo

Google Autocomplete Suggestions

Oct 17th, 2024
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. import streamlit as st
  2. import requests
  3. import json
  4. import time
  5.  
  6. # Function to get Google Autocomplete data
  7. def get_google_autocomplete(keyword):
  8.     url = f"http://suggestqueries.google.com/complete/search?client=firefox&q={keyword}&gl=us&hl=en"
  9.    
  10.     headers = {
  11.         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0"
  12.     }
  13.    
  14.     response = requests.get(url, headers=headers)
  15.    
  16.     if response.status_code == 200:
  17.         suggestions = json.loads(response.text)[1]
  18.         return suggestions
  19.     else:
  20.         st.error(f"Failed to retrieve data for {keyword}. Status code: {response.status_code}")
  21.         return []
  22.  
  23. # Streamlit interface
  24. st.title("Google Autocomplete Suggestions")
  25. search_query = st.text_input("Enter Your Keyword:")
  26.  
  27. if st.button('Get Suggestions'):
  28.     if search_query:
  29.         letters = 'abcdefghijklmnopqrstuvwxyz'
  30.         all_suggestions = []
  31.        
  32.         with st.spinner('Fetching suggestions...'):
  33.             for letter in letters:
  34.                 query = f"{search_query} {letter}"
  35.                 suggestions = get_google_autocomplete(query)
  36.                
  37.                 if suggestions:
  38.                     all_suggestions.extend(suggestions)
  39.                 # Sleep to avoid overwhelming the server
  40.                 time.sleep(1)
  41.  
  42.         if all_suggestions:
  43.             st.success(f"Suggestions for '{search_query}':")
  44.             for suggestion in all_suggestions:
  45.                 st.write(suggestion)
  46.            
  47.             # Option to download suggestions as a text file
  48.             suggestions_str = "\n".join(all_suggestions)
  49.             st.download_button(
  50.                 label="Download Suggestions as Text",
  51.                 data=suggestions_str,
  52.                 file_name=f"{search_query}_suggestions.txt",
  53.                 mime="text/plain"
  54.             )
  55.         else:
  56.             st.warning("No suggestions found.")
  57.     else:
  58.         st.warning("Please enter a keyword to search.")
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement