0

I have this code below to get comments from a page. Sometimes there are no comments, hence the except code triggers. It tries the try code block for like 5-10 seconds before executing the except code. Is there any faster way to check if the elements is found or not? Preferably: If the elements is not found then execute the except code directly.

try: 
        comments = WebDriverWait(driver, 20).until(
            EC.presence_of_all_elements_located((By.XPATH, relativeXpathToReportComments)))
        # some code to be executed if the elements is found

except:
        print("could not find/get comments on comment page")
AppCreator
  • 241
  • 1
  • 2
  • 11

1 Answers1

0

In case you want to check elements existence immediately you can simply use something like this:

if driver.find_elements_by_xpath('relativeXpathToReportComments'):
    # some code to be executed if the elements is found
else:
    print("could not find/get comments on comment page")

driver.find_elements returns a list of elements matching the passed locator.
In case there are such elements it returns non-empty list of found elements. Otherwise it returns an empty list recognized as False in Python.
find_elements and find_element are looking to find elements up to the timeout defined by ImplicitWait which is 0 by default.

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • `find_elements` will take exact same time from `ImplicitWait` there won't be any change – cruisepandey Jun 03 '21 at 11:11
  • @cruisepandey the default value of `ImplicitWait` is 0 – Prophet Jun 03 '21 at 11:12
  • and You assumed that OP had set it to 0 ? – cruisepandey Jun 03 '21 at 11:13
  • You do not need to set it to any value. It is 0 until you change it. So, since he didn't mention that - yes. It's not recommended to use `ImplicitWait` at all until you are aware what is it doing and how it works... – Prophet Jun 03 '21 at 11:15
  • Where is it mentioned that it is not _recommended_ ? it's one of the famous wait Selenium has. To the real side, your solution will not make any time change with respect to time saving as same OP intended – cruisepandey Jun 03 '21 at 11:21
  • @cruisepandey well, I was sure you know this.. https://stackoverflow.com/a/28067495/3485434 – Prophet Jun 03 '21 at 11:33
  • read what official says here not some random one from SO - https://www.selenium.dev/documentation/en/webdriver/waits/ – cruisepandey Jun 03 '21 at 11:34