MarkusF
MarkusF

Reputation: 23

Python XPath selector not working with selenium

I tried to automate some inputs. For this I need to input some text after the
tag. To identify the place where to input I tried XPath for fowlloing HTML code.

<span data-offset-key="1dq3m-0-0">
  <br data-text="true">
</span>

Here is what I wrote in python.

buf_comp_text = 'foobar'
el_xp_comp_text = '//*[@data-text]'

...

## create post in queue (comment)
print('create post in queue - text')
post_txt = driver.find_element_by_xpath(el_xp_comp_text).send_keys(buf_comp_text)


Unfortunately I alwas get error message:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@data-text]"}

Any hint is appreciated.

Upvotes: 2

Views: 341

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193308

Instead of targetting the <br> tag you need to target the <span> tag you can use the following Locator Strategy:

  • Using css_selector:

    buf_comp_text = 'foobar'
    driver.find_element_by_css_selector("span[data-offset-key]").send_keys(buf_comp_text)
    
  • Using xpath:

    buf_comp_text = 'foobar'
    driver.find_element_by_xpath("//span[@data-offset-key][.//br[@data-text]]").send_keys(buf_comp_text)
    

Ideally, to send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategy:

  • Using CSS_SELECTOR:

    buf_comp_text = 'foobar'
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[data-offset-key]"))).send_keys(buf_comp_text)
    
  • Using XPATH:

    buf_comp_text = 'foobar'
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@data-offset-key][.//br[@data-text]]"))).send_keys(buf_comp_text)
    
  • 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
    

Reference

You can find a couple of relevant discussions in:

Upvotes: 1

Related Questions