Blueice Blueice - 3 months ago 12
Python Question

Selenium with Python: First instance of the element is identified but the next occurance is ElementNotVisibleException

I have the following Selenium Test for Python/Django application:

class EmailRecordsTest(StaticLiveServerTestCase):

def test_can_store_email_and_retrieve_it_later(self):
self.browser.get(self.live_server_url)
emailbox = self.browser.find_element_by_xpath("//form[@class='pma-subscribe-form']/input[1]")
self.assertEqual(emailbox.get_attribute("placeholder"), 'Enter your Email')
print("tested until here")
print("The placeholder: ", emailbox.get_attribute("placeholder"))
print(emailbox)
emailbox.send_keys('vio@mesmerizing.com')


First occurance of emailbox is clearly identified as seen from the print runs and assert Equal for placeholder. The last instance of emailbox.send_keys throws following error:

selenium.common.exceptions.ElementNotVisibleException: Message:
Element is not currently visible and so may not be interacted with


Cannot find why the same element become Not Visible when using with send_keys.

The Html code being tested is as below:

<!-- Start footer -->
<footer id="pma-footer">
<!-- start footer top -->
<div class="pma-footer-top">
<div class="container">
<div class="pma-footer-top-area">
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-3">
<div class="pma-footer-widget">
<h4>News letter</h4>
<p>Get latest update, news & offers</p>
<form class="pma-subscribe-form">
<input id="subscribe-email" type="email" placeholder="Enter your Email">
<button class="btn btn-danger btn-md" type="submit">Subscribe!</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end footer top -->


Kindly help.

Answer

Actually find_element returns element which would be present on the DOM no matter it's visible or not and you can get attribute of this element as well but send_keys does an action on element and selenium does action only visible element, So you need to be sure before doing action on element that it's visible using WebDriverWait as below :-

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

wait = WebDriverWait(driver, 10)

emailbox = wait.until(EC.visibility_of_element_located((By.ID, "subscribe-email")))

#do your all stuff before send keys 

# now use send_keys
emailbox.send_keys('vio@mesmerizing.com')

Edited :- If you are still unable to interact with element try using execute_script() to set value as below :-

emailbox = wait.until(EC.presence_of_element_located((By.ID, "subscribe-email")))

#do your all stuff before send keys 

# now use execute_script
driver.execute_script("arguments[0].value = 'vio@mesmerizing.com'", emailbox)