Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
Pavel Zagalsky Avatar asked Oct 19 '22 11:10

Pavel Zagalsky


1 Answers

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()
like image 94
alecxe Avatar answered Oct 23 '22 01:10

alecxe