'Gogle search python

I want to make a program: after entering keywords, the program will automatically enter google and return results as shown. image

this is my code

import requests
from bs4 import BeautifulSoup


def query():
    user_query = input('Enter your query: ')

    URL = "https://www.google.co.in/search?q=" + user_query

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.57'
    }

    page = requests.get(URL, headers=headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    result = soup.find(class_='Uo8X3b OhScic zsYMMe').get_text()
    print(result)


while True:
    try:
        query()
    except Exception:
        print('Sorry no result, please be clear')
    user_input = input('To continue press y: ')
    if user_input != 'y':
        break

My program is not showing any results Thanks for help



Solution 1:[1]

I believe your soup.find is filtering the wrong element class. Google Search HTML Elements

Start from it's parent class and get the first span element instead.

from bs4 import BeautifulSoup

markup = '''
<div jscontroller="GCSbhd" jsaction="SKAaMe:c0XUbe;rcuQ6b:npT2md">
  <div jscontroller="GCSbhd" class="kno-rdesc" jsaction="seM7Qe:c0XUbe;Iigoee:c0XUbe;rcuQ6b:npT2md">
    <h3 class="Uo8X3b OhScic zsYMMe">Description</h3>
    <span>Cristiano Ronaldo dos Santos Aveiro GOIH ComM is a Portuguese professional footballer who plays as a forward for Premier League club Manchester United and captains the Portugal national team.</span>
    <span>
      <span></span>
      <a class="ruhjFe NJLBac fl" href="https://en.wikipedia.org/wiki/Cristiano_Ronaldo" data-ved="2ahUKEwiwl4qG3q72AhUPhlYBHdJvDvYQmhN6BAhFEAI" ping="/url?sa=t&amp;source=web&amp;rct=j&amp;url=https://en.wikipedia.org/wiki/Cristiano_Ronaldo&amp;ved=2ahUKEwiwl4qG3q72AhUPhlYBHdJvDvYQmhN6BAhFEAI">Wikipedia</a>
    </span>
  </div>
</div>
'''
soup = BeautifulSoup(markup,"html.parser")
result_element = soup.find('div', class_='kno-rdesc').find('span')

print(result_element.get_text())

Result:

$ python main.py 
Cristiano Ronaldo dos Santos Aveiro GOIH ComM is a Portuguese professional footballer who plays as a forward for Premier League club Manchester United and captains the Portugal national team.

Note: Google Team might have different class names in different servers or change it over time. You may want to use more filters if you managed to acquire them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Toots