Find and fill input field using Selenium

59 Views Asked by At

I want to create a bot to fill the blank on site. But unfortunately it does not work; I mean does not see or I don't know what is its problem.

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from datetime import datetime


def login_at_specific_time(username, password, target_time):
    driver_path = "path_to_driver"
    
    options = webdriver.ChromeOptions()
    options.binary_location = driver_path
    driver = webdriver.Chrome(options=options)

    website_url = "https://www.instagram.com/accounts/login/?source=auth_switcher" 
    driver.get(website_url)

    while True:
        current_time = datetime.now().strftime("%H:%M")

        if current_time >= target_time:
           
            username_field = driver.find_element(By.ID, "usernameUserInput")
            username_field.send_keys(username)

            password_field = driver.find_element(By.ID, "password")
            password_field.send_keys(password)

            break

        time.sleep(10)

    driver.quit()

login_at_specific_time(username="aabbcc", password="12345678a", target_time="21.45")
1

There are 1 best solutions below

0
On

Here's sending the username to the username input.

It lets the page load first, then looks for the input element (Instagram's happens to include HTML attribute name=username).

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
website_url = "https://www.instagram.com/accounts/login/?source=auth_switcher"
driver.get(website_url)

wait = WebDriverWait(driver, 10)
username_field = wait.until(EC.presence_of_element_located((By.NAME, "username")))

username_field.send_keys("some_username_or_variable")

time.sleep(10)
driver.quit()

Ideally, the page would load the username and password fields at the same time, so you can add that in without an issue. Wrap this in your time functionality properly.


Additionally, I'd refactor your loop to be some format of:

while datetime.now().strftime("%H:%M") < target_time: 
    pass

username_field = driver.find_element(...