Your imports are incorrect. Rather create a function and make a call to the function. I have created the following and used it in a few projects as ready made in the past. Adjust this to your need, keeping in mind that you might need the function again for another project.
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def translate_english_to_hindi(text_to_translate):
try:
# Launch a Chrome browser window and go to the Google Translate website
driver = webdriver.Chrome()
driver.get('https://translate.google.com/')
# Find the source language input box and the target language input box
source_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//textarea[@id="source"]')))
target_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@id="gt-res-dir-ctr"]//textarea[@id="gt-res-dir-ctr"]')))
# Enter the sentence into the source box OR into your input1 box and submit it
source_box.send_keys(sentence)
source_box.send_keys(Keys.RETURN)
# Wait for the translation to appear and extract the Hindi translation, time set to 10 seconds
translation_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//span[@class="tlid-translation translation"]')))
hindi_translation = translation_box.text
# Close the browser window and show the Hindi translation
driver.quit()
return hindi_translation
except TimeoutException:
print("Error: Your translation timed out at/not found within 10 seconds")
return None
except Exception as e:
print("Error:", e)
return None
To make the call, you can use the following -
input1 = "Find your next course. Class Central aggregates courses from many providers to help you find the best courses on almost any subject, wherever they exist"
hindi_translation = translate_english_to_hindi(input1)
if hindi_translation is not None:
print(hindi_translation)
else:
print("Translation failed")