Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the focused element in Selenium

What I'm dealing with

In one of my tests I need to interact with a pop-up input field that is very hard to select using a regular css selector or xpath. I know, however, that this pop-up box will have the focus.

How can I use the fact that it's focused to properly assert that the input field contains some text?

Pseudocode of what I'm looking for:

element = driver.find_element_by_FIND_THE_ELEMENT_WITH_FOCUS
assert elem.text == "foobar"

Partial solutions I've come across:

Possibly a working solution in Ruby:

element = @driver.find_element :css, 'input:focus'
sleep(3)

element.send_keys "Hello WebDriver!"
assert_equal(element.attribute('value'),"Hello WebDriver!")

Getting the focused element with jQuery:

var focus = $(document.activeElement);

Could you provide a solution in python please?

EDIT:

Here's the HTML of the element:

<div class="css-1492t68">Select a speaker...</div>

I realized my question could've lead to some confusion as the element itself is does not have the semantic <input> tag but is rather a <div>. I suppose this is handled by the quill-editor library, which our dev team used when designing this app.

Here's a screenshot of the pop-up box:

Screenshot of the pop-up

like image 956
CrispJam Avatar asked Aug 14 '26 13:08

CrispJam


1 Answers

Since the element does not have a consistent CSS class, using an XPath expression is probably going to be your best bet.

You need to wait for the element to be clickable (which means intractable) by matching a <div> that contains the expected text, and has a CSS class that begins with css-. Doing this should allow enough time for JavaScript to do its thing in the browser to initialize the quill-editor and display it:

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

xpath = "//div[starts-with(@class, 'css-')][contains(., 'The text you expect to find')]"
expected_condition = ExpectedConditions.element_to_be_clickable((By.XPATH, xpath))
element = WebDriverWait(driver, 20).until(expected_condition)

If this pop up field is directly inside a particular parent element, you can further limit your xpath expression accordingly.

If this succeeds, no error will be thrown. If it does not succeed, it should throw a WebDriverTimeoutException (or whatever this error is called in Python).

like image 185
Greg Burghardt Avatar answered Aug 16 '26 09:08

Greg Burghardt