Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write value to hidden element with selenium python script

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!!

like image 479
vikram Avatar asked Feb 24 '13 06:02

vikram


People also ask

How does Python handle hidden elements in Selenium?

In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden. Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page.

Can Selenium interact with hidden elements?

Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method.

How do I get hidden text in an element?

In some cases, one may find it useful to get the hidden text, which can be retrieved from element's textContent , innerText or innerHTML attribute, by calling element. attribute('attributeName') . element. getAttribute("textContent") worked for me.


1 Answers

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'")
like image 163
Hui Zheng Avatar answered Sep 27 '22 19:09

Hui Zheng