I have a dataframe df. I am trying to send the values present in the column 'fruit' to the google translate page using send_keys() method in Selenium and python. Below is an example code that replicates what I am trying to do.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
# Create a test dataframe
fruit = ['This is apple', 'This is orange', 'This is mango']
bucket = ['A', 'B', 'C']
df = pd.DataFrame({"fruit": fruit, "bucket": bucket})
# create a new Firefox session
driver = webdriver.Firefox()
# Wait for the page to load
driver.implicitly_wait(5)
# Maximize the browser window
driver.maximize_window()
# navigate to the home page
driver.get("https://translate.google.co.in/")
# Locate the text field to update values
text_field = driver.find_element_by_name("text")
# Clears any value already present in text field
text_field.clear()
# Updates the string 'Breaking Bad' in search bar
text_field.send_keys(df['fruit'])
text_field.send_keys(Keys.ENTER)
Although it works, the rows are all being sent as a single line like this:
This is appleThis is orangeThis is mango
I want the values to appear in the google translate page like this:
This is apple
This is orange
This is mango
Any help on how to make this happen would be really appreciated. I have Python 3.6.6 and my selenium version is 3.141.0. My OS is Windows 10 (64 Bit).
You can try to send concatenated string as
text_field.send_keys(" ".join(df['fruit']))
or with new-line characters:
text_field.send_keys("\n".join(df['fruit']))
P.S. Instead of using Selenium to translate strings you can use GoogleTranslateAPI python binding:
In Terminal/CommandLine:
pip install git+https://github.com/BoseCorp/py-googletrans.git
In Python shell/IDE:
from googletrans import Translator
translator = Translator()
# Translate into "es" (Spanish)
print(translator.translate(" ".join(df['fruit']), dest='es').text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With