selenium: fill form only when requested

25 views
Skip to first unread message

sezb51

unread,
May 25, 2022, 7:26:22 AM5/25/22
to Selenium Users
Hello,

after so many google queries on how to do selenium stuff... :)
I want to "give back" to wider community my nice python/selenium code which inject an "AutoFill Form" button to a web page. Only after being press it then the form get filled.
This can be useful should you want to show a website but you don't want to spend time typing on many input fields so you leverage on selenium as companion tool....

The below example just use google search page and send_keys to the input field after pressing the self-destroying "AutoFill Form" button (so same function can be reused in other section/pages)

Have fun.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

def wait_for_user_input(x, y):
   autofill_btn="""
     // create button element
     var btn = document.createElement('button');
     btn.setAttribute("id", "automation");
     btn.innerText = "AutoFill Form";
     // styling it as button
     btn.style.cursor = "pointer"
     btn.style.color = "red";
     btn.style.fontWeight = "bold";
     btn.style.backgroundColor = "yellow";
     btn.style.borderStyle = "solid";
     btn.style.borderRadius = "25px";
     // positioning it
     btn.style.position = "absolute";
     btn.style.top = "{x}px";
     btn.style.left = "{y}px";
     btn.style.padding = "10px";
     // when select it self remove
     btn.onclick = function () {
       element = document.getElementById('automation');
       element.remove();
     };
     var body = document.body;
     body.appendChild(btn);
   """
   autofill_btn = autofill_btn.replace("{x}", str(x))
   autofill_btn = autofill_btn.replace("{y}", str(y))
   driver.execute_script(autofill_btn)
   while (len(driver.find_elements(By.ID, "automation"))>0):
     time.sleep(2)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))


wait_for_user_input(100, 300)

driver.find_element(By.XPATH, '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input').send_keys("this is a test")

input("Press Enter to quit Chrome...")
driver.quit()
Reply all
Reply to author
Forward
0 new messages