How to pass data dynamically from JSON file to Selenium automated login with Python

Question:

So I’m using Python and I have a JSON file that has usernames and passwords in the following format

{
"username": {
    "0": "user1",
    "1": "user2",
    },
"password": {
    "0": "user1pass",
    "1": "user2pass",
    }
}

I’m trying to import credentials from the JSON file into Selenium

username = driver.find_element(By.NAME, "username")
password = driver.find_element(By.NAME, "password")
username.send_keys("test")
password.send_keys("test")

so for example it would pull data of User 1 from the JSON file and pass it into the username field, login then do smth,, then log out and pull the second user etc

I want to do a loop that can extract data from JSON and also work with Selenium to use the data and go to next data etc..not just pulling the data.

What should I be looking for exactly?

Asked By: xFranko

||

Answers:

You need to have a loop of numbers which then in each iteration finds the login form and using loop variable chooses username and password then do things that you want.

credentials_dict = {
"username": {
    "0": "user1",
    "1": "user2",
},
"password": {
    "0": "user1pass",
    "1": "user2pass",
}
for i in range(0,2):
    username = driver.find_element(By.NAME, "username")
    password = driver.find_element(By.NAME, "password")
    username.send_keys(credentials_dict['username'][str(i)])
    password.send_keys(credentials_dict['password'][str(i)])
    # do things that you want to do.
Answered By: Mojtaba
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.