Site icon FSIBLOG

How to Build Your Own ‘Search Google or Type a URL’ Page with Python

Search Google or Type a URL

Search Google or Type a URL

Have you ever wished your browser’s start page could do two things let you type in a website URL or just type a search and hit enter and have it intelligently decide whether to navigate or search, Learn exactly how to build your own “Search Google or Type a URL” page with Python.

Why Build this Project

Most browsers already let you type in the address bar and automatically detect if you entered a full URL (like example.com) or a search query (like “best pizza near me”). But building your own version helps you learn how this decision logic works, how to combine UI + Python + web redirection, and gives you a custom start-page you can host or personalise.

Comparing Existing Tutorials

Before we build, let’s see what others have done and how this tutorial will be better and more detailed. I looked at three strong competitor articles:

  1. “A search engine in 80 lines of Python” by Alex Molas.
    • Strengths: Builds an actual mini search engine with crawling, indexing.
    • Weaknesses: It’s much more complex and deals with search engine internals (crawler, index) rather than the simpler “search or URL” start page. Doesn’t focus on redirect UI or decision logic.
    • Missing: Front-end UI, URL vs search detection logic, ready-to-deploy start page.
  2. **“Let’s Build a Search Engine” from Anvil blog.
    • Strengths: Clear explanation of search engine components with Python.
    • Weaknesses: Again, focused on crawling, indexing, ranking not on the simpler, practical “enter URL or search” interface.
    • Missing: Minimal start page implementation, URL handling, UI code.
  3. “How to Use Google Custom Search Engine API in Python” from ThePythonCode blog.
    • Strengths: Gives detailed API usage for Google CSE in Python, with example code.
    • Weaknesses: It’s about searching Google via API, not about UI + URL detection + redirect logic for a start page.
    • Missing: The user interface part, the URL navigation part, the decision logic.

Project Overview & Architecture

What We’re Building

You’ll build a simple web page with a single input field and a “Go” button. When the user types:

Architecture

Workflow

  1. User types text in input box and hits enter or clicks Go.
  2. Front-end submits that text to the back-end (or builds a redirect link directly).
  3. Back-end logic:
    • Check if input matches URL pattern (with or without scheme).
    • If yes → redirect to that URL (ensuring we add scheme if missing).
    • If no → redirect to https://www.google.com/search?q=<encoded query>.
  4. Browser receives redirect and navigates accordingly.

Writing the Interface (HTML/JS)

In templates/index.html, you’ll write something like this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Search or Enter URL</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
    input[type=text] { width: 60%; padding: 10px; font-size: 1.2em; }
    button { padding: 10px 20px; font-size: 1.2em; }
  </style>
</head>
<body>
  <h1>Search or Type a URL</h1>
  <form id="searchForm" action="/go" method="post">
    <input type="text" name="q" id="q" placeholder="Type search terms or a URL" autocomplete="off">
    <button type="submit">Go</button>
  </form>

  <script>
    const form = document.getElementById('searchForm');
    form.onsubmit = function(e) {
      const input = document.getElementById('q').value.trim();
      if (!input) {
        e.preventDefault();
        alert('Please type something!');
      }
    };
  </script>
</body>
</html>

Explanation

Of course, you can tweak styling, add logo, etc.

Implementing the Python logic

Now open app.py and write the back-end logic:

from flask import Flask, request, redirect, render_template
import re
import urllib.parse

app = Flask(__name__)

# Regex pattern to detect URLs (very simple)
URL_PATTERN = re.compile(
    r'^(?:https?://)?'      # optional scheme
    r'(?:www\.)?'           # optional www
    r'[^ \n]+\.[^ \n]+'     # contains a dot and more characters
    r'(?:/.*)?$'            # optional path
    , re.IGNORECASE
)

def looks_like_url(s: str) -> bool:
    return bool(URL_PATTERN.match(s))

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/go', methods=['POST'])
def go():
    raw = request.form.get('q', '').strip()
    if not raw:
        return redirect('/')
    if looks_like_url(raw):
        # ensure scheme
        if not raw.lower().startswith(('http://','https://')):
            raw = 'https://' + raw
        return redirect(raw)
    else:
        # treat as search query
        query = urllib.parse.quote_plus(raw)
        return redirect(f'https://www.google.com/search?q={query}')

if __name__ == '__main__':
    app.run(debug=True)

Explanation

Note on Regex

The regex is intentionally simple to keep things easy. If you want more robust URL detection (ports, subdomains, IP addresses, international domains, etc.) you can improve the regex or use Python’s urllib.parse to try parsing. But for this project the simple approach works fine.

Integrating with Google Search

Because your project uses Google Search rather than building your own search index, know the following:

Use a different search engine

If you prefer DuckDuckGo or Bing or a private search provider, you can change the redirect URL accordingly. For example:

return redirect(f'https://duckduckgo.com/?q={query}')

That flexibility is part of the fun.

Deployment & Hosting

Once your app works locally (visit http://127.0.0.1:5000/, type something, and see correct behaviour), you’ll want to deploy. Here are simple steps:

Heroku (free tier)

  1. Sign up/log in to Heroku.
  2. Create a new app (choose region nearest you).
  3. Add a Procfile in your project root: web: gunicorn app:app
  4. Create requirements.txt: pip freeze > requirements.txt
  5. Ensure you have gunicorn in requirements.txt: pip install gunicorn
  6. Commit your code to a git repository.
  7. Push to Heroku remote.
  8. Visit your Heroku URL. It should load your interface.

Self hosting / VPS

Make it your browser home page

Once hosted, you can set your browser’s home page to the app URL. Every time you open a new tab you land there—it becomes your custom “search or URL” start page.

Extensions & next steps

Now for the fun part. Once you have the basic version working, here are some ideas to extend and personalise it:

Custom search provider

Allow users to select search engine (Google, DuckDuckGo, Bing) via a dropdown.

Keywords/shortcuts

Add logic so if you type e.g. yt cats, it redirects to youtube.com/search?q=cats. Or w python goes to Wikipedia search. Basically “shortcut keyword → predefined URL pattern”.

History of recent entries

Use a tiny SQLite database (or JSON file) to store the last 10 entries the user typed and display them underneath the input box as clickable links.

Mobile friendly UI

Improve the HTML/CSS so the page looks good on mobile devices: responsive design, larger input, centred alignment.

Browser extension wrap

Wrap your page as a browser extension (Chrome/Firefox) so pressing your browser’s extension icon opens the interface popup.

Offline fall-back

If you detect no internet connection, show a friendly message instead of redirecting.

URL sanitisation and security

Ensure the URL you redirect to is safe (avoid javascript:… or data:… URLs). Implement checks or allow‐list/deny-list.

Each of these adds value and makes your project richer.

Conclusion

You now have everything you need to build your own “Search Google or Type a URL” page with Python. We walked through the idea, setup, front-end code, back-end logic, deployment, and extension ideas. Compared with other tutorials, this one is simpler, focused on the start-page behaviour, and adds unique items like URL detection, redirect logic, and customisation tips.

Exit mobile version