Selenium2+python automation 36 - judging element existence

foreword

Recently, many friends have been asking how to determine whether an element exists. This method is not available in selenium, so you need to write it yourself.

If the element does not exist, the operation element will report an error, or if there are multiple elements, an error will be reported when they are not unique. This article introduces two methods for determining the existence of an element.

One, find_elements method judgment

1. The find_elements method is a method to find all the same attributes on the page. This method is actually very easy to use. There are not many people who can master the skills. The editor will play its effect this time.

2. Since there are many ways to locate elements, it is also more troublesome if the positioning methods are not uniform when judging. Here I choose css positioning (some students who like xpath can use xpath syntax by themselves)

3. Write a function judgment, return True if found, and return False if not found (or more than one)

2. Baidu input box as an example

1. Determine whether the element with id kw exists

2. Determine whether the label is an input element or not

3. Determine whether the element with id of xxx exists

Three, catch exception method

1. If no element is found, an exception will be thrown and return False

2. Return True if the element is found

3. But this method has a drawback. If there are multiple identical elements on the page, it will also return True (that is, as long as there are elements on the page, it will return True, no matter how many)

4. Reference code

# coding:utf-8
from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
def is_element_exist(css):
    s = driver.find_elements_by_css_selector (css_selector=css)
    if len(s) == 0:
        print "Element not found: %s"%css
        return False
    elif len(s) == 1:
        return True
    else:
        print "Found %s elements: %s "%(len(s),css)
        return False

# Determine if there is an element with id kw on the page
if is_element_exist("#kw"):
    driver.find_element_by_id("kw").send_keys("yoyoketang")
# Determine the page Whether there is a label for the input element
if is_element_exist("input"):
    driver.find_element_by_tag_name("input").send_keys("yoyoketang")
# 判断页面有无id为xxx的元素
if is_element_exist("xxx"):
    driver.find_element_by_id("xxx").send_keys("yoyoketang")

def isElementExist(css):
    try:
        driver.find_element_by_css_selector(css)
        return True
    except:
        return False

print isElementExist("#xxx")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325348160&siteId=291194637