Andersson
Andersson

Reputation: 52685

How to get rid of Cannot focus element exception

I faced with following issue with chromedriver: I have a text input field and a texarea. I can successfully send text to both elements with follow code

input = driver.find_element_by_xpath('//input[@type="text"]')
input.send_keys('test')
textarea = driver.find_element_by_xpath('//textarea[not(@readonly)]')
textarea.send_keys('test')

But if to try this code

text_fields = driver.find_elements_by_xpath('//*[input[@type="text"] or textarea[not(@readonly)]]')
for field in text_fields:
    field.send_keys('test')

I get selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element

P.S. Adding field.click() before sending text or using ActionChains failed to solve issue. Also len(text_fields) return 2, so both elements correctly matched with XPath

Upvotes: 1

Views: 2269

Answers (1)

Florent B.
Florent B.

Reputation: 42528

The second expression will return the parent element of the input or textarea. If you wish to get both in a single XPath then:

text_fields = driver.find_elements_by_xpath("//input[@type='text'] | //textarea[not(@readonly)]")
for field in text_fields:
    field.send_keys('test')

Or with a CSS selector :

text_fields = driver.find_elements_by_css_selector("input[type='text'] , textarea:not([readonly])")
for field in text_fields:
    field.send_keys('test')

Upvotes: 1

Related Questions