背景:在做自动化测试过程中,经常会出现一种报错selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {“method”:“name”,“selector”:“email”}。
一般有三种原因: 1、定位的方法或者属性写的有问题。 2、延迟等待时间不够。 3、有iframe。
背景:在做自动化测试过程中,经常会出现一种报错selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {“method”:“name”,“selector”:“email”}。
一般有三种原因: 1、定位的方法或者属性写的有问题。 2、延迟等待时间不够。 3、有iframe。
一般iframe有几种处理方式: 1、如果iframe有id或者name我们可以直接driver.switch_to.frame(’****’)。括号里边就是写具体的id或者name对应的值。 例如: driver.switch_to.frame(‘x-URS-iframe’) 复制代码
2、没有id、name或者id、name是动态的,我们可以 driver.switch_to.frame(driver.find_element_by_class_name(‘ddd’)) # 切入 通过classname、xpath、css等多种方式。 具体代码: dd = driver.find_element_by_xpath("//div[@id=‘loginDiv’]/iframe") driver.switch_to.frame(dd) 复制代码
3、也可以通过索引, driver.switch_to.frame(0)这个索引是针对当前的iframe的。 然后上边截图中的就很简单呐了,我们只需要先进入iframe,然后再进入他下的iframe,然后再执行我们的查找定位方式就可以定位到。 具体代码如下: iframes = driver.find_elements_by_tag_name(“iframe”) driver.switch_to.frame(iframes[0]) 复制代码 切入iframe后就需要切出iframe,那么如何实现,看两个api吧: driver.switch_to.parent_frame()#从子frame切回到父frame 复制代码 def parent_frame(self): “”" Switches focus to the parent context. If the current context is the top level browsing context, the context remains unchanged.
:Usage: driver.switch_to.parent_frame() """ self._driver.execute(Command.SWITCH_TO_PARENT_FRAME)复制代码
driver.switch_to.default_content()#切回主文档 复制代码 def default_content(self): “”" Switch focus to the default frame.
:Usage: driver.switch_to.default_content() """ self._driver.execute(Command.SWITCH_TO_FRAME, {'id': None})