简体   繁体   中英

How do I check if an element is present in selenium (python 2) without throwing a NoSuchElement Exception if it isn't?

I would like to check whether an element is present on the page I am testing but I don't want the find_element_by_xpath function to throw a NoSuchElement Exception if it isn't present. Here's my current code:

try:
    self.driver.find_element_by_xpath(an_element)

    try:
        self.driver.find_element_by_xpath(another_element)

    except NoSuchElementException:
        ... (If the first find_element works and second doesn't I want this code)

except NoSuchElementException:
    ... (If the first find_element fails I want this code)

This is essentially functioning as an if else statement so I would prefer to use an if else statement so that I could find a different no such element exception within these code blocks.

Is there another option other that doesn't throw an exception if the element is not present?

EDIT:

The answers given work great! Thanks to those who answered. I also figured out another way if you're reading this with the same problem:

When you use find_element s _by_xpath() it returns a list of elements found. If this list has a length of 0 then the element is not present. If length is 1 element is present. No exception thrown.

You can use below code:

if self.driver.find_elements_by_xpath(an_element):
    if self.driver.find_elements_by_xpath(another_element):
        # code for case both found
    else:
        # second not found
else:
    # first not found

Note that find_elements_by_xpath() returns you list of WebElements or empty list. No need to handle NoSuchElementException

You can search into page_source, where there are all html tags and content :

if '<button class="">' in self.driver.page_source:
    ... (do one thing)
else:
    ... (do another thing)

The code you have is exactly correct for doing this kind of thing. In Python, try/except is a valid control structure to use like this and is often (almost always) more efficient than using an if/else block. You may also want to simplify your code by splitting it up into different functions, like the example below (in response to edit).

class SomeClass(object):
    """Your class which is doing the scraping"""

    def find_element(self, xpath):
        """A handy function to try and find the element.

        Args:
            xpath (str): the xpath string you are trying to find

        Returns:
            List of elements
        """
        try:
            return self.driver.find_element_by_xpath(xpath)
        except NoSuchElementException:
            return []

    def find_buttons(self):
        """method to find your buttons

        Returns:
            list of buttons, or empty list if no buttons found
        """
        # define your queries
        xpaths = ['/some/query', '/some/other/query']

        # iterate through them
        for xpath in xpaths:
            buttons = self.find_element(xpath)
            if buttons:
                # until you are successful 
                return buttons

        # or return empty list if no buttons found
        return []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM