SoFunction
Updated on 2024-10-29

A short summary of the two ways selenium determines whether an element exists or not

There is no corresponding method in selenium, you need to write it yourself.

  • Element exists but is not unique, manipulating the element will report an error
  • The element does not exist, and manipulating the element will also report an error

The first: catching exceptions

Cons: As long as there are elements on the page, not several, all return True

from selenium import webdriver
import unittest
class Test1():
# I. Prepare browser drivers, website addresses
# setUp is run before each test function is run, case sensitive; self cannot be omitted
 def setUp(self):
 =()
 =""
 
# II. Open a browser and send a request
 Function names must begin withtestbeginning
 def test_01(self):
 browser=
 ()
# IV. Calling methods to determine if an element exists
 flag=(self,“input”)
 if flag:
  print(“The element exists”)
 else:
  print(“The element does not exist”)
# III. Methods for determining whether an element exists
 def isElementExist(self):
 flag=True
 browser=
 try:
  browser.find_element_by_css_selector(element)
  return flag
 except:
  flag=False
  return flag
# V. Run all test methods that begin with test
if __name__=="__main__":
 ()

Second: find_elements method

# Same as above except step 3
def isElementExist(self):
 flag=True
 browser=
 ele=browser.find_elements_by_css_selector(element)
 if len(ele)==0:
 flag=False
 return flag
 if len(ele)==1:
 return flag
 else:
 flag=False
 return flag 

to this article on selenium to determine the existence of an element of the two methods of summary of the article is introduced to this, more related selenium to determine the existence of meta content, please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!