Pavel Zagalsky
Pavel Zagalsky

Reputation: 1646

Checking if HTML element exists with Python Selenium

I am trying to check if an element exists on an HTML page with Selenium/Python.

This is my function:

class runSelenium(object):

    def __init__(self):
        # define a class attribute
        self.driver = webdriver.Firefox()

    def isElementPresent(self, locator):
        try:
            self.driver.find_element_by_xpath(locator)
        except NoSuchElementException:
            print ('No such thing')
            return False
        return True

    def selenium(self):
        self.driver.get("https://somepage.com")
        isElement = self.isElementPresent("//li[@class='item'][6]")
        isElement1 = str(isElement)


    if __name__ == '__main__':
        run = runSelenium()
        run.selenium()

I am trying to pick the result with a Boolean value but with no luck:

isElement = self.isElementPresent("//li[@class='item'][6]")

What am I missing here?

Upvotes: 5

Views: 10092

Answers (2)

Pavel Zagalsky
Pavel Zagalsky

Reputation: 1646

So I restarted the IDE (Visual Studio 2013) and it works now fine.. The code is correct 100%

Upvotes: -2

alecxe
alecxe

Reputation: 474171

You need to un-indent the last code block:

class runSelenium(object):

    def __init__(self):
        # define a class attribute
        self.driver = webdriver.Firefox()

    def isElementPresent(self, locator):
        try:
            self.driver.find_element_by_xpath(locator)
        except NoSuchElementException:
            print ('No such thing')
            return False
        return True

    def selenium(self):
        self.driver.get("https://somepage.com")
        isElement = self.isElementPresent("//li[@class='item'][6]")
        isElement1 = str(isElement)


if __name__ == '__main__':
    run = runSelenium()
    run.selenium()

Upvotes: 5

Related Questions