Yaakov Bressler
Yaakov Bressler

Reputation: 12008

Copy text from environment variable and paste in Selenium (Python)

I'm trying to paste a massive amount of text to an input element with Selenium using Python 3.8 on an Ubuntu OS. I can iterate over my string and send_keys, but that takes more than 60 seconds. I was hoping I could copy my text from my Python code and paste into the session with Ctrl + V:

I wish this worked...

# How big do you want your character chunks?
n_chunk_size = 500

if len(keyphrase)>n_chunk_size:
    pyperclip.copy(keyphrase)
    input_element.send_keys(Keys.CONTROL, 'v')

Slow way:

from textwrap import wrap
for k in wrap(keyphrase, n_chunk_size):
    input_element.send_keys(k)

Upvotes: 1

Views: 914

Answers (1)

Zvjezdan Veselinovic
Zvjezdan Veselinovic

Reputation: 547

So, this answer, actually, differs. If the textbox that you're working with is for a company, chances are that the input textbox might have a maxcharacter limit. So, you might need to check the length of your string prior to inserting it into the textbox.

For this example, I used the W3Schools input textbox and inserted my environment variables into the textbox. In this example, I imported

import os as OperatingSystem

and was able to get my computer's environment variables using this command:

# Get our operating system's environment information
environment_info = str(OperatingSystem.environ)

From there, I was able to create a for-loop that checked the input text of our textbox and compared the length of the input text to our environment_info's length.

MAIN PROGRAM - For Reference

from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver as ChromeDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as DriverWait
from selenium.webdriver.support import expected_conditions as DriverConditions
from selenium.common.exceptions import WebDriverException
import os as OperatingSystem
import time

def get_chrome_driver():
    """This sets up our Chrome Driver and returns it as an object"""
    path_to_chrome = "F:\Selenium_Drivers\Windows_Chrome85_Driver\chromedriver.exe"
    chrome_options = webdriver.ChromeOptions()

    # Browser is displayed in a custom window size
    chrome_options.add_argument("window-size=1500,1000")

    return webdriver.Chrome(executable_path = path_to_chrome,
                            options = chrome_options)


def wait_displayed(driver : ChromeDriver, xpath: str, int = 5):
    try:
         DriverWait(driver, int).until(
            DriverConditions.presence_of_element_located(locator = (By.XPATH, xpath))
        )
    except:
        raise WebDriverException(f'Timeout: Failed to find {xpath}')


# Get our operating system's environment information
environment_info = str(OperatingSystem.environ)

# Gets our Chrome driver and opens our site
chrome_driver = get_chrome_driver()
chrome_driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_test")
wait_displayed(chrome_driver, "//iframe[@id='iframeResult']")
wait_displayed(chrome_driver, "//div[contains(@class, 'CodeMirror-wrap')]")

# Go into our iFrame
iFrame_Element = chrome_driver.find_element(By.XPATH, "//iframe[@id='iframeResult']")
chrome_driver.switch_to.frame(iFrame_Element)
wait_displayed(chrome_driver, "//form[contains(@action, 'action_page')]")
wait_displayed(chrome_driver, "//input[@id='fname']")
wait_displayed(chrome_driver, "//input[@id='lname']")

# Enter our information into our input textbox
chrome_driver.find_element(By.XPATH, "//input[@id='fname']").clear()
chrome_driver.find_element(By.XPATH, "//input[@id='fname']").send_keys(environment_info)

# Check that our textbox has been populated fully
for counter in range(5):
    if chrome_driver.find_element(By.XPATH, "//input[@id='fname']").get_attribute('value').__len__() != environment_info.__len__():
        if counter == 4:
            raise Exception("Failed to input data into our textbox")
        else:
            time.sleep(3)
            print(f'Counter is: {counter}')
    else:
        print('Input Textbox populated successfully')
        break

chrome_driver.quit()
chrome_driver.service.stop()

Upvotes: 1

Related Questions