Flask web-app input for selenium browser automation

Viewed 3634

I have a simple Flask web app for logging into my electric company dashboard. I have a page called essentials. The essentials page has a form set up, for user input.

from flask import Flask, render_template, request 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.common.by import By import time

app = Flask(__name__)
@app.route('/') 
def home():
    return render_template('home.html')

@app.route('/essentials') 
def essentials():
    return render_template('essentials.html')

@app.route('/form', methods=['POST']) 
def form():
    username = request.form.get("user_name")
    password = request.form.get("password") 

if __name__ == '__main__':
    app.run(debug=True)

Then i have some selenium code for filling user authentication form automatically:

driver = webdriver.Safari()
driver.set_window_size(1100, 800)

driver.get('https://www.firstenergycorp.com/content/customer/jersey_central_power_light.html')
    
username = 
password = 
    
    
driver.find_element_by_id('loginUsername').send_keys(username)
driver.find_element_by_id('loginPwd').send_keys(password)
driver.find_element_by_id('loginPwd').send_keys(Keys.RETURN)
time.sleep(7)

Question: How do i pass the flask form web user inputs (username, password), into the selenium variables in this case username and password that it will then use for the automation part?

1 Answers

If you are submitting a form with method POST, then you can try this

@app.route('/form', methods=['GET', 'POST']) 
def form():
    if flask.request.method == 'POST':
        username = request.form.get("user_name")
        password = request.form.get("password") 
        
        driver = webdriver.Safari()
        driver.set_window_size(1100, 800)

        driver.get('https://www.firstenergycorp.com/content/customer/jersey_central_power_light.html')

        driver.find_element_by_id('loginUsername').send_keys(username)
        driver.find_element_by_id('loginPwd').send_keys(password)
        driver.find_element_by_id('loginPwd').send_keys(Keys.RETURN)
        time.sleep(7)
    
    else:
        # what do you want to display if method is not "post"

References:

  1. Flask docs
  2. Handling GET and POST in same Flask view
  3. Flask example with POST
Related