search
HomeBackend DevelopmentPython TutorialSelenium exception handling in Python

Selenium exception handling in Python

May 04, 2018 pm 03:49 PM
pythonseleniumdeal with

This article mainly introduces Selenium exception handling in PHPPython. It has certain reference value. Now I share it with you. Friends in need can refer to it.

During the execution of automated tests, it is inevitable that there will be If an error/exception occurs, for example, if the test script does not find the corresponding element, a NoSuchElementException will be thrown immediately. Don't be afraid at this time, there must be something wrong with the test script or the test environment! So how to deal with it is the key? Because there is usually only a local problem, in order to allow the script to continue executing, we can use try...except...raise to catch the exception. After catching the exception, the corresponding exception cause can be printed out, which facilitates analysis of the exception cause.

The following will give an example. When an exception is thrown, the information is printed on the console and the current browser window is intercepted. This can be used as a basis for subsequent bugs to better locate the problem for the corresponding developer. The code is as follows:

import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException  #导入NoSuchElementException
class ExceptionTest(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://www.baidu.com")
  def test_exception(self):
    driver = self.driver
    try:
      search_text = driver.find_element_by_id("ss")
      self.assertEqual('百度一下', search_text.get_attribute("value"))
    except NoSuchElementException:
      file_name = "no_such_element.png"
      #driver.save_screenshot(file_name)
      driver.get_screenshot_as_file(file_name) 
      raise  #抛出异常,注释后则不抛出异常
  def tearDown(self):
    self.driver.quit()
if __name__ == '__main__':
  unittest.main(verbosity=2)

There is an exception when running, and the result is as follows:

## WebDriver is used in the above code The built-in method of capturing the screen and saving it, such as the save_screenshot(filename) method and save_screenshot_as_file(filename) method here, when the test exception is thrown, capture the browser screen at the same time and save it in the specified path with a custom image file name (above) code is the current path).


Another example is when an element is presented in the DOM, but it is invisible and cannot be interacted with, an exception will be thrown. Take the login on Baidu homepage as an example, when the element cannot be invisible , throwing an ElementNotVisibleException exception, the code is as follows:

import unittest
from selenium import webdriver
from selenium.common.exceptions import ElementNotVisibleException  #导入ElementNotVisibleException
class ExceptionTest(unittest.TestCase):
  def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://www.baidu.com")
  def test_exception(self):
    driver = self.driver
    try:
      login = driver.find_element_by_name("tj_login")
      login.click()
    except ElementNotVisibleException:
      raise  
  def tearDown(self):
    self.driver.quit()
if __name__ == '__main__':
  unittest.main(verbosity=2)

There is an exception during operation, the result is as follows:

The following will list common exceptions in selenium:

Related recommendations:


A simple analysis of the xlsxwriter library in python

For loop and range built-in functions in python

In-depth understanding of the time module in python

The above is the detailed content of Selenium exception handling in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

How does the memory footprint of a list compare to the memory footprint of an array in Python?How does the memory footprint of a list compare to the memory footprint of an array in Python?May 02, 2025 am 12:08 AM

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

How do you handle environment-specific configurations when deploying executable Python scripts?How do you handle environment-specific configurations when deploying executable Python scripts?May 02, 2025 am 12:07 AM

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.