Created
June 21, 2020 02:36
-
-
Save amandaroos/cf8a1f68fb20eb3fa491914876054565 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from selenium import webdriver | |
from selenium.common.exceptions import TimeoutException | |
from selenium.webdriver.support.ui import WebDriverWait | |
from selenium.webdriver.support import expected_conditions as EC | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.chrome.options import Options | |
def translate(word, codes): | |
#Choose phrase to translate and enter the array of language codes you would like the phrase to be translated to | |
text= word | |
language_codes = codes | |
translations_dictionary = {} | |
#Enter the path to the chromedriver.exe, headless means the browser GUI won't be created | |
options = Options() | |
options.add_argument('--headless') | |
options.add_argument('--disable-gpu') | |
driver = webdriver.Chrome(executable_path=r'path to chromedriver.exe', chrome_options=options) | |
elementPresent = True | |
for code in language_codes: | |
myUrl = "https://translate.google.com/?sl#view=home&op=translate&sl=en&tl=" + code + "&text=" + text | |
driver.get(myUrl) | |
delay = 1 # seconds | |
try: | |
print("in try1 " + code) | |
element = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, r"/html/body/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/div[2]/div[3]/div[1]/div[2]/div/span[1]/span"))) | |
except TimeoutException: | |
elementPresent = False | |
if not elementPresent: | |
elementPresent = True | |
try: | |
print("in try2") | |
element = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, r"/html/body/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/div[2]/div[3]/div[1]/div[2]/div/span[1]"))) | |
except TimeoutException: | |
print ("Loading took too much time! " + code) | |
element_text = element.text | |
translations_dictionary[code] = element_text | |
driver.quit() | |
#Return the dictionary of completed translations | |
return translations_dictionary |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment