How to create a simple google search in python

When you search for an information in google it displays the list of all results which is associated with your search.We can perform the similar task by programming using python within 10 lines of code.This is a fun part of programming in which we can create a simple google search within 10 lines of coding.

First of all fire up the terminal and check whether python3 is installed

Required libraries to perform google search in python

1.Requests
2.sys
3.webbrowser
4.bs4 (Beautiful Soup)

If any of these libraries are not installed do the following

If you had python3 then the command to install these packages are

pip3 install requests

pip3 install sys

pip3 install webbrowser

pip3 install bs4

Uses of these libraries:

Requests library is to request the search url from the user

sys.argv is a list in Python, which contains the command-line arguments passed to the script.

webbrowser is used to display the requested information to the user in the browser

Beautiful Soup is a Python library for pulling data out of HTML and XML file

Source code:

import requests,sys,webbrowser,bs4
res=requests.get(‘https://google.com/search?q=’+”.join(sys.argv[1:]))
res.raise_for_status()
soup=bs4.BeautifulSoup(res.text,”html.parser”)
linkElements=soup.select(‘.r a’)
linkToOpen=min(10,len(linkElements))
for i in range(linkToOpen):
    webbrowser.open(‘https://google.com’+linkElements[i].get(‘href’))

Code Explanation:

1.Import all the required libraries which are mentioned above

2.Then request the user to input the search term in the command line argument so that we have used sys.argv to get the input in the command line.

3.This line checks the status of the search term and the result produced

4.This line initiates Beautiful soup which is retrieve all the html and xml files associated with the search term from the resultant sites.

5.This line uses regular expressions to separate the anchor tags which is link from all the websites which is associated with the users search term

6.This line tells how many link to open for the search term.You can any number of links to open for your search term.

7.Then loop over all the resultant links and then display it in the browser using the webbrowser library.

If you run the program by specifying the search term by

Python filename.py “search term” 


You should specify the search term inside the double quotation otherwise there will be a error.It will provide all the result associated with the search.
The output will be displayed in your default browser 
I hope you have enjoyed the post.Thanks for reading the post and please do share the post and make your valuable comments.

LEAVE A REPLY

Please enter your comment!
Please enter your name here