在操作selenium时,UI自动化中经常会遇到元素识别不到,找不到的问题,原因有很多,比如不在iframe里,xpath或id写错了等等;但有一种是在当前显示的页面元素不可见,拖动下拉条后元素就出来了。
错误背景:函数在前八次调用均找到,在第九次时报错,如下
Traceback (most recent call last):
File "d:/works/codes/practice-code/BC_requires/windows_filter/webui-new.py", line 131, in <module>
testpage(driver,i,mainwindow)
File "d:/works/codes/practice-code/BC_requires/windows_filter/webui-new.py", line 44, in testpage
driver.find_element_by_xpath(url).click()
File "D:\Program Files\Anaconda3\envs\python2\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=96.0.4664.110)
问题界面为网页为:
原因分析:该元素为页面不显示,需要下拉框来选择该元素,
可用方法如何 :
1、使用js脚本直接操作,
方法如下:
js="var q=document.getElementById('id').scrollTop=10000"
driver.execute_script(js)
或:
js="var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)
这里的id为滚动条的id,但js中没有xpath的方法,所以滚动条没有id的网页此方法不适用
2、使用js脚本拖动到特定地方
target = driver.find_element_by_id("id_keypair")
driver.execute_script("arguments[0].scrollIntoView();", target) #拖动到可见的元素去
这个方法可以将滚动条拖动到需要显示的元素位置,此方法用途比较广,可以使用
3、根据页面显示进行变通,发送tab键
在本例中的页面中,密码是输入框,正常手工操作时,可以通过tab键会切换到密码框中,所以根据此思路,在python中也可以发送tab键来切换,使元素显示
from selenium.webdriver.common.keys import Keys
driver.find_element_by_id("id_login_method_0").send_keys(Keys.TAB)
4、使用RF框架中的focus函数,
前段时间使用robotframe work框架时,selenium2library里面有一个非常好用的功能Focus,会自动定位到元素,研读一下源码:
def focus(self, locator):
"""Sets focus to element identified by `locator`."""
element = self._element_find(locator, True, True)
self._current_browser().execute_script("arguments[0].focus();", element)
从源码中我们可以看到,此方法与我们在python自己写的方法二)一致,工具给我们做了封装。
参考文章:
https://www.cnblogs.com/landhu/p/5761794.html
https://blog.youkuaiyun.com/qq_37814780/article/details/109356171