python + selenium encounters an element not locate the problem, the way to record yourself this error (error selenium.common.exceptions.NoSuchElementException)

Today selenium when writing a script to send mail, encounter some page elements not found error. After repeated testing yourself, find a cause Baidu, finally resolved. Briefly summarize it, there are the following reasons:
a: Frame controls nested, .Frame / Iframe can not locate the elements:
general mailbox we often use nested frame considered typical, they are usually registered to log in a frame control inside, the title and the text frame may be nested iframe, took with me today in the script as an example (qq-mail)

you can see, if we want to find the recipient, the title will advance to the first Frame control , otherwise it will error, but if you also want to find the body element, it is necessary to enter the second ifame control
can be used self.driver.switch_to.frame (incoming or id xpath value) method into the Frame control. Note (original driver.switch_to_frame () This method webdriver3.0 has not supported)
noteworthy point is: if I want to click on the send button at this time I would need to exit iframe control, because at this time is not sent in the body iframe control is on them, so no matter how you position, also located less.
At this point we need to use switch_to.default_content () this method. This method is that no matter what level you are in control of the frame, just call this method will return to the original page. If I want to find the send button, you have to re-enter the frame controls to find
html interface structure as
is this question let me toss a nest morning, summarize it: we have a multi-level nested Frame problem, we must first look closely HTML structure, do not worry locate, observe good conduct in the structure down, like me, a waste of time province.

二:.页面还没有加载出来,就对页面上的元素进行的操作:
        这种情况一般说来,可以设置等待,等待页面显示之后再操作,这与人手工操作的原理一样:
        1设置等待时间;缺点是需要设置较长的等待时间,案例多了测试就很慢;
        2设置等待页面的某个元素出现,比如一个文本、一个输入框都可以,一旦指定的元素出现,就可以做操作。
        3在调试的过程中可以把页面的html代码打印出来,以便分析。
        解决方案:
        导入时间模块。(或者利用隐式等待或者显式等待)
        import time
        time.sleep(3)
 三:利用xpath进行定位:
        由于Xpath层级太复杂,容易犯错。虽然有人说xpath不好,但它真的功能很强大,可以找到父亲/祖先,这是其他方式都做不到的,如果遇到定位不到元素不妨试试xpath
        解决方案:
        1可以使用Firefox的firePath,复制xpath路径。该方式容易因为层级改变而需要重新编写过xpath路径,不建议使用,初学者可以先复制路径,然后尝试去修改它。
        2提高下写xpath的水平。
        这里推荐一篇文章吧:[selenium+python元素定位方法总结](http://https://www.cnblogs.com/yufeihlf/p/5717291.html)
        该博文详细总结了Xpath的使用,多组合定位一般都能实现定位问题。

        如何检验编写的Xpath是否正确?编写好Xpath路径,可以直接复制到搜狐浏览器的firebug查看html源码,通过Xpath搜索:如下红色框,若无报错,则说明编写的Xpath路径没错。
        find_element_by_xpath("//input[@id='kw']")
        
        (注:如果是动态元素,直接使用xpath进行定位)
    四:不可见元素定位

           如上百度登录代码,通过名称为tj_login查找的登录元素,有些是不可见的,所以加一个循环判断,找到可见元素(is_displayed())点击登录即可。

Guess you like

Origin www.cnblogs.com/lxc1997ye/p/11596115.html