Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Import necessary libraries: requests and BeautifulSoup from bs4.
  2. Define the Google search URL and a search query string.
  3. Use the requests library to retrieve the HTML data from the search query URL.
  4. Parse the HTML data using BeautifulSoup.
  5. Find the div element with class "med" which contains a message that says "Your search - [search query] - did not match any documents."
  6. Check if the message exists in the HTML data, which means the search returned zero results.
  7. Print a message to the user indicating whether the search returned zero results or not.

The following is an example Python code:

import requests
from bs4 import BeautifulSoup

# define search query and URL
search_query = "example search query"
url = f"https://www.google.com/search?q={search_query}"

# retrieve HTML data from search query URL
response = requests.get(url)
html_data = response.text

# parse HTML data using BeautifulSoup
soup = BeautifulSoup(html_data, 'html.parser')

# find div element with class "med" which contains message for zero results
zero_results_div = soup.find("div", {"class": "med"})

# check if message for zero results exists in HTML data
if zero_results_div and "did not match any documents" in zero_results_div.text:
    print(f"No results found for: {search_query}")
else:
    print(f"Results found for: {search_query}")

Note that this method may not work if Google changes its HTML structure or if it detects that your code is scraping its search results. Therefore, it's important to be respectful of Google's terms of service and to use this code for educational purposes only.