Selenium2+python Automation 57-catch Exception (nosuchelementexception)

Source: Internet
Author: User
Tags xpath

Objective

When locating elements, often encounter various anomalies, why these anomalies occur, and how to deal with the exception?

This article learns the cause of the anomaly by learning Selenium's exceptions module.

First, an exception occurred

1. Open the Blog home page, locate the "new essay" element, this element id= "blog_nav_newpost"

2. To deliberately let it fail, I add xx after the element attribute

3. After a run failure as shown, the program is interrupted on this line of the lookup element and will not continue to execute the Click event.

Second, catch the exception

1. In order for the program to continue to execute, we can use try...except ... Catches an exception. The exception can be printed out after catching the exception, so that the cause of the exception is analyzed

2. As can be seen from the following anomalies, the cause of the exception is: nosuchelementexception

Selenium.common.exceptions.NoSuchElementException:Message:Unable to locate element: {"method": "id", "selector": " Blog_nav_newpostxx "}

3. Import Nosuchelementexception class from Selenium.common.exceptions

Third, the reference code:

# Coding:utf-8
From selenium import Webdriver
From selenium.common.exceptions import nosuchelementexception
Driver = Webdriver. Firefox ()
Driver.get ("http://www.cnblogs.com/yoyoketang/")
# Positioning homepage "new essay"
Try
element = Driver.find_element ("id", "blog_nav_newpostxx")
Except Nosuchelementexception as msg:
Print U "Find element exception%s"%msg

# click on the element # Chat QQ Group: 232607095
Else
Element.click ()

Iv. common anomalies of selenium

1.NoSuchElementException: no element found

2.NoSuchFrameException: no IFrame found

3.NoSuchWindowException: Window handle not found handle

4.NoSuchAttributeException: Property Error

5.NoAlertPresentException: No alert pop-up box found

6.lementNotVisibleException: Element not visible

7.ElementNotSelectableException: Element not selected

8.TimeoutException: Find element timeout

V. Other anomalies and source code

1. In the Lib directory: Selenium/common/exceptions interested can see

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# Distributed with the additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); Except in compliance
# with the License. Obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# unless required by applicable or agreed to writing,
# Software distributed under the License is distributed in an
# ' As is ' BASIS, without warranties OR CONDITIONS of any
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""
Exceptions that could happen in all the Webdriver code.
"""


Class Webdriverexception (Exception):
"""
Base Webdriver exception.
"""

def __init__ (self, msg=none, Screen=none, Stacktrace=none):
self.msg = Msg
Self.screen = Screen
Self.stacktrace = StackTrace

def __str__ (self):
Exception_msg = "Message:%s\n"% self.msg
If Self.screen is not None:
Exception_msg + = "screenshot:available via screen\n"
If Self.stacktrace is not None:
StackTrace = "\ n". Join (Self.stacktrace)
Exception_msg + = "stacktrace:\n%s"% Stacktrace
Return exception_msg


Class Errorinresponseexception (webdriverexception):
"""
Thrown when a error has a occurred on the server side.

This could happen when communicating with the Firefox extension
or the remote driver server.
"""
def __init__ (self, Response, msg):
Webdriverexception.__init__ (self, msg)
Self.response = response


Class Invalidswitchtotargetexception (webdriverexception):
"""
Thrown when frame or window target is switched doesn ' t exist.
"""
Pass


Class Nosuchframeexception (invalidswitchtotargetexception):
"""
Thrown when frame target is switched doesn ' t exist.
"""
Pass


Class Nosuchwindowexception (invalidswitchtotargetexception):
"""
Thrown when window target is switched doesn ' t exist.

To find the current set of active Windows handles, you can get a list
Of the active window handles in the following::

Print Driver.window_handles

"""
Pass


Class Nosuchelementexception (webdriverexception):
"""
Thrown when element could is found.

If you encounter this exception, your may want to check the following:
* Check your selector used in your find_by ...
* Element may not yet is on the screen at the time of the find operation,
(webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait ()
For what to write a, wait wrapper to wait for the element to appear.
"""
Pass


Class Nosuchattributeexception (webdriverexception):
"""
Thrown when the attribute of element could is not being found.

Want to check if the attribute exists in the particular browser
Testing against. Some browsers may has different property names for the same
Property. (IE8 's. InnerText vs. Firefox textcontent)
"""
Pass


Class Staleelementreferenceexception (webdriverexception):
"""
Thrown when a reference to an element are now "stale".

Stale means the element no longer appears on the DOM of the page.


Possible causes of staleelementreferenceexception include, but not limited to:
* You is no longer on the same page, or the page could have refreshed since the element
was located.
* The element may be been removed and re-added to the screens, since it was located.
Such as an element being relocated.
This can happen typically with a JavaScript framework when values is updated and the
node is rebuilt.
* Element May has been inside an IFRAME or another context which is refreshed.
"""
Pass


Class Invalidelementstateexception (webdriverexception):
"""
"""
Pass


Class Unexpectedalertpresentexception (webdriverexception):
"""
Thrown when a unexpected alert is appeared.

Usually raised when a expected modal is blocking webdriver form executing any
More commands.
"""
def __init__ (self, msg=none, Screen=none, Stacktrace=none, Alert_text=none):
Super (unexpectedalertpresentexception, self). __init__ (msg, screen, stacktrace)
Self.alert_text = Alert_text

def __str__ (self):
Return "Alert Text:%s\n%s"% (Self.alert_text, super (unexpectedalertpresentexception, self). __str__ ())


Class Noalertpresentexception (webdriverexception):
"""
Thrown when switching to no presented alert.

This can being caused by calling a operation on the alert () class when a alert is
Not yet on the screen.
"""
Pass


Class Elementnotvisibleexception (invalidelementstateexception):
"""
Thrown when a element is present on the DOM, but
It was not visible, and so was not a able to being interacted with.

Most commonly encountered if trying to click or read text
Of an element, that is, hidden from view.
"""
Pass


Class Elementnotselectableexception (invalidelementstateexception):
"""
Thrown when trying to select an unselectable element.

For example, selecting a ' script ' element.
"""
Pass


Class Invalidcookiedomainexception (webdriverexception):
"""
Thrown when attempting to add a cookie under a different domain
than the current URL.
"""
Pass


Class Unabletosetcookieexception (webdriverexception):
"""
Thrown when a driver fails to set a cookie.
"""
Pass


Class Remotedriverserverexception (webdriverexception):
"""
"""
Pass


Class TimeoutException (webdriverexception):
"""
Thrown when a command does not complete in enough time.
"""
Pass


Class Movetargetoutofboundsexception (webdriverexception):
"""
Thrown when the target provided to the ' Actionschains ' Move ()
method is invalid, i.e. out of document.
"""
Pass


Class Unexpectedtagnameexception (webdriverexception):
"""
Thrown when a support class does not get a expected web element.
"""
Pass


Class Invalidselectorexception (nosuchelementexception):
"""
Thrown when the selector which was used to find a element does not return
A webelement. Currently this only happens when the selector are an XPath
expression and it is either syntactically invalid (i.e. it's not a
XPath expression) or the expression does not select WebElements
(e.g. "Count (//input)").
"""
Pass


Class Imenotavailableexception (webdriverexception):
"""
Thrown when the IME is not available. This exception are thrown for every ime-related
Method call if IME support is not available on the machine.
"""
Pass


Class Imeactivationfailedexception (webdriverexception):
"""
Thrown when activating a IME engine has failed.
"""
Pass

The study process has encountered the question, may add selenium (Python+java) QQ Group Exchange: 232607095

Feel that you have help, in the lower right corner of a praise it, thank you support!

Selenium2+python Automation 57-catch Exception (nosuchelementexception)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.