You want to use JSON test data to fill a login form in Selenium Python. The JSON file login.json contains:
hard📝 Application Q15 of 15
Selenium Python - Data-Driven Testing
You want to use JSON test data to fill a login form in Selenium Python. The JSON file login.json contains:
{"username": "user1", "password": "pass1"}
Which code snippet correctly reads the JSON and uses Selenium to fill the form fields with ids user and pass?
Aimport json
with open('login.json') as f:
data = json.load(f)
driver.find_element_by_name('user').send_keys(data['username'])
driver.find_element_by_name('pass').send_keys(data['password'])
Bimport json
with open('login.json') as f:
data = json.load(f)
driver.find_element('id', 'user').send_keys(data['username'])
driver.find_element('id', 'pass').send_keys(data['password'])
Cimport json
with open('login.json') as f:
data = json.loads(f)
driver.find_element_by_id('user').send_keys(data['username'])
driver.find_element_by_id('pass').send_keys(data['password'])
Dimport json
with open('login.json') as f:
data = json.load(f)
driver.find_element('name', 'user').send_keys(data['username'])
driver.find_element('name', 'pass').send_keys(data['password'])
Step-by-Step Solution
Solution:
Step 1: Correctly read JSON file
json.load(f) reads JSON from file object correctly; json.loads() expects a string, so import json
with open('login.json') as f:
data = json.loads(f)
driver.find_element_by_id('user').send_keys(data['username'])
driver.find_element_by_id('pass').send_keys(data['password']) is wrong.
Step 2: Use correct Selenium locator method
driver.find_element('id', 'user') is the modern syntax to find element by id; find_element_by_id() is deprecated.
Step 3: Match locators with element ids
The form fields have ids 'user' and 'pass', so locating by id is correct, not by name.
Final Answer:
import json
with open('login.json') as f:
data = json.load(f)
driver.find_element('id', 'user').send_keys(data['username'])
driver.find_element('id', 'pass').send_keys(data['password']) -> Option B