问题
This is the HTML code in question:
<textarea rows="1" cols="1" name="text" class=""></textarea>
This is my code:
msgElem = driver.find_element_by_css_selector("textarea[name='text']")
driver.execute_script("arguments[0].click();", msgElem)
driver.execute_script("arguments[0].value = 'Whats up mate, how you doin';", msgElem)
msgElem.submit()
The code executes and nothing happens. I assume it selects the textarea but doesn't type nothing into it? or nothing happens at all. It also finds the element so I assume I don't need to wait for the textarea to be visible. When I don't use js and just do
msgElem = driver.find_element_by_css_selector("textarea[name='text']")
msgElem.send_keys('Whats up mate, how you doin')
It gives me ElementNotInteractableException.
回答1:
This error message...
ElementNotInteractableException
...implies that the WebDriver instance was unable to interact with the desired element as the Element was Not Interactable.
Analysis
The Locator Strategy which you have used actually identifies two elements within the HTML DOM and the parent element of the first matching element contains the attribute style="display:none"
as follows:
<form action="#" class="usertext cloneable warn-on-unload" onsubmit="return post_form(this, 'comment')" style="display:none" id="form-dyo">
<input type="hidden" name="thing_id" value="">
<div class="usertext-edit md-container" style="">
<div class="md">
<textarea rows="1" cols="1" name="text" class=""></textarea>
</div>
Hence you see ElementNotInteractableException.
Solution
To send a character sequesce to the desired element you need to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following Locator Strategies:
Using
CSS_SELECTOR
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.title + div textarea[name='text']"))).send_keys("Sowik")
Using
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='message']//following::div[1]//textarea[@name='text']"))).send_keys("Sowik")
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
来源:https://stackoverflow.com/questions/61984794/selenium-wont-type-to-textarea-and-raises-elementnotinteractableexception