Python – Use Python to send values from a dataframe using send_keys() in Selenium

Use Python to send values from a dataframe using send_keys() in Selenium… here is a solution to the problem.

Use Python to send values from a dataframe using send_keys() in Selenium

I have a data frame df. I’m trying to send the value present in the “fruit” column to the google translate page using the send_keys() method in Selenium and python. Below is a sample code that replicates what I’m 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, all lines are sent as a single line, as follows:

This is appleThis is orangeThis is mango

I want these values to appear in the Google Translate page like this:

This is apple
This is orange
This is mango

Any help on how to achieve this would be appreciated. I have Python 3.6.6 and my version of selenium is 3.141.0. My operating system is Windows 10 (64-bit).

Solution

You can try sending the string for the connection as

text_field.send_keys(" ".join(df['fruit']))

or newline:

text_field.send_keys("\n".join(df['fruit']))

P.S. Instead of using Selenium, you can use GoogleTranslateAPI python binding instead of using Selenium:

In the terminal/command line:

pip install git+https://github.com/BoseCorp/py-googletrans.git

In the Python shell/IDE:

from googletrans import Translator

translator = Translator()
#  Translate into "es" (Spanish)
print(translator.translate(" ".join(df['fruit']), dest='es').text)

Related Problems and Solutions