今天在使用 selenium 对CodeMirror-code类型的文本域对象使用send_keys方式输入内容时,发现这种方式不生效了
image.png
尝试代码方式:
# 组件内容
b.find_element_by_name("codemirror").send_keys(content)
# 点击保存按钮
b.find_element_by_css_selector("div.componentProgramAddOrEdit-form button.el-button.el-button--primary").click()
time.sleep(0.5)
print("创建[%s]编程组件成功!" % name)
执行后结果报错:
Traceback (most recent call last):
File "/Users/sleeli/Desktop/programfile/PycharmProjects/testBSC/BCC V3.1/start.py", line 70, in <module>
createPrograms(b,"组件编程01")
File "/Users/sleeli/Desktop/programfile/PycharmProjects/testBSC/BCC V3.1/ProgramManager.py", line 57, in createPrograms
createProgram(browser, pname, pdesc, classname, pcontent)
File "/Users/sleeli/Desktop/programfile/PycharmProjects/testBSC/BCC V3.1/ProgramManager.py", line 32, in createProgram
b.find_element_by_name("codemirror").send_keys(content)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 479, in send_keys
'value': keys_to_typing(value)})
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=78.0.3904.108)
通过查询.ElementNotInteractableException: Message: element not interactable错误查询发现是因为这个对象是在页面是不可见的,看来不能按正常方法进行输入操作了
最终查询和尝试解决方法如下:
经过查找发现因为默认情况下文本框是display: none;,即使不可见的状态,需要先使用鼠标点击激活后才能进行输入操作
# 找到文本框
# e = b.find_element_by_name("codemirror") # 第一次通过名称找的文本框找错了 发现还有一个
e = b.find_element_by_css_selector(".CodeMirror textarea") #
# 找到所在输入的行对象
p = b.find_element_by_css_selector("pre.CodeMirror-line")
#对做所在行进行点击操作,激活文本框
p.click()
# 在文本框中输入内容
e.send_keys("Hello, World!")
执行效果,成功输入字符串
image.png
说明:
在.CodeMirror下找到的textarea并不是name=codemirror的
image.png
网友评论