5

I'm trying to write to a text box with my python selenium code but get an error since a parent tag of the text box is hidden.

driver.find_element_by_xpath("//input[@itemcode='XYZ']").send_keys(1)

I see a Javascript executor workaround with java but need help with something similar for python script.

Thanks in advance!!

1 Answer 1

8

Try this workaround(tested in Firefox and Chrome):

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.Firefox() # Get local session(use webdriver.Chrome() for chrome) 
browser.get("http://www.example.com") # load page from some url
assert "example" in browser.title # assume example.com has string "example" in title

try:
    # temporarily make parent(assuming its id is parent_id) visible
    browser.execute_script("document.getElementById('parent_id').style.display='block'")
    # now the following code won't raise ElementNotVisibleException any more
    browser.find_element_by_xpath("//input[@itemcode='XYZ']").send_keys(1)
    # hide the parent again
    browser.execute_script("document.getElementById('parent_id').style.display='none'")
except NoSuchElementException:
    assert 0, "can't find input with XYZ itemcode"

Another workaround is even simpler(assuming the text box's id is "XYZ", otherwise use any JS code that can retrieve it) and probably better if you only want to change the text box's value:

browser.execute_script("document.getElementById('XYZ').value+='1'")
Sign up to request clarification or add additional context in comments.

1 Comment

what if the element has an id that keeps changing? can we find it by class name or css selector and then make it visible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.