Search code examples
javascriptpythonhtmlseleniumtwitter

Selenium Error in python : NoSuchElementException ./ancestor-or-self::form


I am trying to make a python script , where I will enter my credentials and tweet text in python console, and the script will login and then tweet , using selenium. All the tasks are done. Just last click on Tweet button is throwing error.

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: ./ancestor-or-self::form

Here is inspect element code related to the tweet button :

<div class="css-1dbjc4n r-urgr8i r-42olwf r-sdzlij r-1phboty r-rs99b7 r-1w2pmg r-1n0xq6e 
r-1vuscfd r-1dhvaqw r-icoktb r-1fneopy r-o7ynqc r-6416eg r-lrvibr" 
aria-haspopup="false" disabled="" role="button" aria-disabled="true" 
data-testid="tweetButtonInline"> 
  <div class="css-901oao r-1awozwy r-jwli3a r-6koalj r-18u37iz r-16y2uox r-1qd0xha r-a023e6 
  r-vw2c0b r-1777fci r-eljoum r-dnmrzs r-bcqeeo r-q4m81j r-qvutc0" dir="auto">
    <span class="css-901oao css-16my406 css-bfa6kz r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0">
    <span class="css-901oao css-16my406 r-1qd0xha r-ad9z0x r-bcqeeo r-qvutc0">Tweet
    </span>
    </span>
  </div>
</div>

Now, I want to select the button and click on it. So I wrote python code as following:

ultim=driver.find_element_by_xpath('//span[@class="css-901oao css-16my406 r-1qd0xha r-ad9z0
r-bcqeeo r-qvutc0"]')
ultim.click()   

OR

ultim=driver.find_element_by_xpath('//span[@data-testid="tweetButtonInLine"]')
ultim.click()

Please, help me click on that Tweet button using selenium in python. I need to make this script and submit for school project. Help is needed and appreciated thanks.


Solution

  • Induce WebDriverWait and element_to_be_clickable() to click on the Tweet button.

    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//span[text()="Tweet"]'))).click()
    

    You need to import following libraries.

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