使用selenium python脚本将值写入隐藏元素

vik*_*ram 5 python selenium

我正在尝试使用我的python selenium代码写入文本框但由于隐藏了文本框的父标记而出现错误.

driver.find_element_by_xpath("//input[@itemcode='XYZ']").send_keys(1)
Run Code Online (Sandbox Code Playgroud)

我看到一个Javascript执行器与java的解决方法,但需要帮助python脚本类似的东西.

提前致谢!!

Hui*_*eng 6

尝试此解决方法(在Firefox和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"
Run Code Online (Sandbox Code Playgroud)

另一种解决方法更简单(假设文本框的id是"XYZ",否则使用任何可以检索它的JS代码),如果你只想更改文本框的值,可能会更好:

browser.execute_script("document.getElementById('XYZ').value+='1'")
Run Code Online (Sandbox Code Playgroud)