Send keys to active element in Selenium Python

2.7k views Asked by At

So I have following element that I need to send keys to:

<input type="text" placeholder="Recipient address" class="text-gray-light py-1.5 sm:py-2 px-2 sm:px-3 bg-gray-dark border-0 block w-full rounded-md focus:ring-blue focus:border-blue" value="">

but there are many elements like this on the page. If I search:

//input[@placeholder="Recipient address"]

I get 35 results (exact same element as above) while finding that XPATH, although, only one is active. The rest are hidden in the DOM. When I try to send keys, I get Element not interactable exception which is normal since there are multiple elements, and driver most likely tries to send keys to the wrong one. Then I tried to create following function:

def try_transfer():
    while True:
        try:
            element = WebDriverWait(driver.instance, 2).until(ec.element_to_be_clickable((By.XPATH, '//input['
                                                                                                    '@placeholder="Recipient address"]')))
            element.is_enabled()
            element.click()
            element.send_keys('HG4sYqvkTfgBvGgZZhYfws4f8BoytTr1NmcDEwkKC2z8')
        except TimeoutException:
            break

I don't get the error white above function, but, it does not send keys to the right element.

Any idea how would I go about finding that specific active element and sending keys to it.

2

There are 2 answers

0
undetected Selenium On BEST ANSWER

As per the documentation activeElement() switches to the element that currently has focus within the document currently "switched to", or the body element if this cannot be detected. This matches the semantics of calling "document.activeElement" in Javascript.

Similarly using using Selenium-Python clients if the desired element is the active element and having the focus you can use the following solution:

elem = driver.switch_to.active_element
elem.send_keys('HG4sYqvkTfgBvGgZZhYfws4f8BoytTr1NmcDEwkKC2z8')
0
Bhavya Lodaya On

You can use index for finding your particular data

If the index you're activating is in 1st position write this xpath

//input[@placeholder="Recipient address"][1].send_keys()

else

(//input[@placeholder="Recipient address"])[2].send_keys() # or 3 or 4 or 5 whatever you want