5

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?

6
  • The function itself looks good, could you elaborate more about what your problem is? Thanks. Commented Apr 13, 2016 at 22:01
  • When i check the isElement variable, it doesn't show me whether it's True or False Commented Apr 13, 2016 at 22:02
  • Could you show how are you using the isElement variable after? Thanks. Commented Apr 13, 2016 at 22:03
  • I try to check it as a Bool and as a String and for both I see 'error, not defined' under the watch in Visual Studio: isElement = self.isElementPresent("//li[@class='badgeList__item'][6]") isElement1 = str(isElement) Commented Apr 13, 2016 at 22:05
  • Could you please post the complete code you have so far, just to see the bigger picture? Commented Apr 13, 2016 at 22:09

2 Answers 2

5

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()
Sign up to request clarification or add additional context in comments.

Comments

-2

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

1 Comment

What is the issue you are seeing here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.