How to make a Google Translation API using Python?
Last Updated :
07 Feb, 2023
Google Translate is a free multilingual translation service, based on statistical and neural machine translation, developed by Google. It is widely used to translate complete websites or webpages from one languages to another.
We will be creating a python terminal application which will take the source language, target language, a phrase to translate and return translated text. We will be implementing unit testing and web scraping techniques with selenium in python. Web scraping is a concept of capturing the required data from a website. Selenium is an industry grade library used for web-scraping and unit testing of various software. As a prerequisite, we will be requiring the following tools to be installed in our system.
- Python 3.x: A version of python 3.0 or above should be installed.
- Selenium library: A python library required for scraping the websites. Copy the following statement to install selenium on your system.
Installation: python3 -m pip install selenium - Webdriver: An instance of a web browser required by selenium to open webpages. Download the latest version of Chrome Webdriver from the link below and save it in the same folder in which your main program is.
Link: https://chromedriver.chromium.org/downloads
We will divide the code section into three portions:
- Setting up the selenium and chrome webdriver tool.
- Taking input and testing for error in input.
- Translating using Google Translate.
Part 1: Setting the selenium tool and webdriver settings.
python3
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import JavascriptException
# local variables
from selenium.webdriver.chrome.options import Options as ChromeOptions
chrome_op = ChromeOptions()
chrome_op.add_argument('--headless')
browser = webdriver.Chrome(executable_path ='chromedriver', options = chrome_op)
- Importing webdriver object to connect to the chrome browser instance.
- Importing keys library to connect the basic keyboard commands to the browser instance.
- Importing exception handlers for browser instance.
- Import browser options and set '--headless' property to run the browser instance in background. Comment the ''chrome_op.add_argument('--headless')" statement to bring the webdriver to foreground processes.
Part 2: Taking input and testing for in input.
python3
def takeInput():
languages = {"English": 'en', "French": 'fr',
"Spanish": 'es', "German": 'de', "Italian": 'it'}
print("Select a source and target language (enter codes)")
print("Language", " ", "Code")
for x in languages:
print(x, " ", languages[x])
print("\n\nSource: ", end ="")
src = input()
sflag = 0
for x in languages:
if(languages[x] == src and not sflag):
sflag = 1
break
if(not sflag):
print("Source code not from the list, Exiting....")
exit()
print("Target: ", end ="")
trg = input()
tflag = 0
for x in languages:
if(languages[x] == trg and not tflag):
tflag = 1
break
if(not tflag):
print("Target code not from the list, Exiting....")
exit()
if(src == trg):
print("Source and Target cannot be same, Exiting...")
exit()
print("Enter the phrase: ", end ="")
phrase = input()
return src, trg, phrase
This is a demo code so the languages code are kept limited to {English, Spanish, German, Italian, French}. You can add more languages and their codes later.
- Taking input for source language and target language code.
- Checking if the codes entered are supported or not.
- Source language and target language code should not be same.
Part 3: Translating using Google Translate:
python3
def makeCall(url, script, default):
response = default
try:
browser.get(url)
while(response == default):
response = browser.execute_script(script)
except JavascriptException:
print(JavascriptException.args)
except NoSuchElementException:
print(NoSuchElementException.args)
if(response != default):
return response
else:
return 'Not Available'
def googleTranslate(src, trg, phrase):
url = 'https://translate.google.co.in/# view = home&op = translate&sl =' + \
src + '&tl =' + trg+'&text ='+phrase
script = 'return document.getElementsByClassName("tlid-translation")[0].textContent'
return makeCall(url, script, None)
- googleTranslate() function receives the three parameters i.e. source code, target code and phrase. It generates the URL for the browser to request for.
- script contains a javascript statement which searches for an HTML element with class = "tlid-translation" and returns it's text contents.
- makeCall() function makes a request with the URL created, executes the script when the webpage is ready and returns the fetched text.
Combining the above three parts.
python3
if __name__ == "__main__":
src, trg, phrase = takeInput()
print("\nResult: ", googleTranslate(src, trg, phrase))
Paste all the parts shown above in a single .py file and execute it using Python3.
Execution: python3 <filename.py>
Output:
Input section :

If you have commented the '--headless' property statement, then a browser window like below, will appear:

The result will appear on the terminal window like below:

Note: This is demo project so language supported are limited. You can increase the language support by adding more language codes in the declaration.
Similar Reads
Language Translator Using Google API in Python
API stands for Application Programming Interface. It acts as an intermediate between two applications or software. In simple terms, API acts as a messenger that takes your request to destinations and then brings back its response for you. Google API is developed by Google to allow communications wit
3 min read
How to Make API Call Using Python
APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see ho
3 min read
How to download Google Images using Python
Python is a multi-purpose language and widely used for scripting. We can write Python scripts to automate day-to-day things. Letâs say we want to download google images with multiple search queries. Instead of doing it manually we can automate the process. How to install needed Module :Â pip install
2 min read
Real-Time Translation App Using Python
In this article, we'll delve into the creation of a potent real-time translation application using Python. Leveraging the capabilities of the Google Translate API, we'll walk you through building an intuitive graphical user interface (GUI) with the Tkinter library. With just a few lines of code, you
5 min read
Google Maps Selenium automation using Python
Prerequisites: Browser Automation using Selenium Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS, and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. It can
4 min read
Python - Morse Code Translator GUI using Tkinter
Prerequisites : Introduction to tkinter | Morse Code Translator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In
6 min read
Python | Build a REST API using Flask
Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
How to Use Google Bard with Python
Google Bard (Currently known as Gemini) is an advanced AI chatbot developed by Google that can help with answering questions, summarizing content, writing creatively, and much more. However, as of now, Google has not released an official API for Bard. But using the open-source Python package bardapi
3 min read
Create a real time voice translator using Python
In this article, we are going to create a real-time voice translator in Python. Module neededplaysound: This module is used to play sound in Pythonpip install playsoundSpeech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Spe
7 min read
Speech Recognition in Python using Google Speech API
Speech recognition means converting spoken words into text. It used in various artificial intelligence applications such as home automation, speech to text, etc. In this article, youâll learn how to do basic speech recognition in Python using the Google Speech Recognition API.Step 1: Install Require
2 min read