Sultan Morbiwala
Sultan Morbiwala

Reputation: 171

How to send text to the textarea as per the html through Selenium and Python

I want to click and send text within a textbox but not able to find the element.

This is the html I want to click and send text-

<form class="addComment expand" data-id="9656414">
<img 
src="https://ctl.s6img.com/society6/img/g2taHIrokQ01R_67jS8ulaWI2wk/h_150,w_150/users/avatar/~artwork/s6-original-art-uploads/society6/uploads/u/sul97/avatar_asset/d837ee10016843a3bba9ae3310cc338d" width="25" height="25">
                                <textarea placeholder="Add a comment..." data-button="9656414"></textarea>
                                <button id="b9656414">Comment</button>
                            </form>

My code:-

driver.find_element_by_class_name('add').click()
comments = driver.find_element_by_xpath("/html/body/form[2]")
comments.click()
comments.send_keys("Awesome Art")

I can click but cant type text on it. What am i doing wrong?

Upvotes: 1

Views: 765

Answers (3)

Ishita Shah
Ishita Shah

Reputation: 4035

If you want to type text on Text Area, You need to locate text area:

driver.find_element_by_xpath("//textarea[@data-button='9656414']")

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193088

As per the HTML you have shared the desired element is a React element so you have to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:

  • CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "form.addComment.expand textarea[placeholder^='Add a comment']"))).send_keys("Awesome Art")
    
  • XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//form[@class='addComment expand']//textarea[contains(@placeholder,'Add a comment')]"))).send_keys("Awesome Art")
    

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

Upvotes: 0

Sers
Sers

Reputation: 12255

You're trying to click and send text to the form itself, not to textarea. Here how you can locate textarea and button inside form.

driver.find_element_by_css_selector("form[class='addComment expand'] textarea").send_keys("Awesome Art")
driver.find_element_by_css_selector("form[class='addComment expand'] button").click()

Upvotes: 0

Related Questions