What's the best way to get the number of elements on a page without triggering an implicit wait if there are no such elements on the page? At the moment, I'm using this:
def get_number_of_elements(self, by, locator):
self.driver.implicitly_wait(0)
elements = self.driver.find_elements(by, locator)
self.driver.implicitly_wait(self.config.IMPLICIT_TIMEOUT)
return count(elements)
This works, but is there a better way of doing this?
UPDATE:
The issue was cause because of the way I was instantiating webdriver.Chrome(options=options
. In short, do not set driver.implicitly_wait()
:
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
if __name__ == '__main__':
options = Options()
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--crash-dumps-dir=tmp')
options.add_argument('--remote-allow-origins=*')
options.add_argument("--no-sandbox")
options.add_argument("--disable-gpu")
options.page_load_strategy = "eager"
options.add_experimental_option("excludeSwitches", ["enable-automation"])
driver = webdriver.Chrome(options=options)
driver.set_page_load_timeout(30)
# driver.implicitly_wait(30) # <-- This triggers an implicit wait of 30 seconds for find_elements if no elements exist.
driver.set_script_timeout(30)
driver.get("https://www.google.com")
driver.find_element(By.XPATH, "//div[text()='Accept all']").click()
driver.find_element(By.NAME, "q").send_keys("Stack Overflow")
driver.find_element(By.XPATH, "//input[@type='submit'][@value='Google Search']").submit()
elements = driver.find_elements(By.XPATH, "//h1[text()='No such thing...']")
print(len(elements))
elements = driver.find_elements(By.XPATH, "//a")
print(len(elements))
time.sleep(5)
driver.close()