I am trying to wait for a few elements in a page to load before continuing with entering/getting data from the page. Some reading has lead me to this kind of code:
#including imports in case they are influencing things
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get('example.com')
try:
element1_present = EC.presence_of_element_located((By.ID, 'id'))
WebDriverWait(driver, timeout).until(element1_present)
except TimeoutException:
print('Timed out waiting for page to load')
#Then get some data from example.com
This works just fine, however, I'd like to determine if the element is present through CSS Selector, not ID. Reference to Selenium documentation is confusing me. It states that the presence_of_element_located method should take a "locator" as an argument, but looking at the By documentation, I do not see how (By.ID, 'id') is a valid locator (though clearly, it works, and I don't understand this), and more specifically, I don't see how to code it to be a CSS Selector locator.
I have attempted By.cssSelector, By.CSS, and other similar terms in place of By.ID, and moving parentheses about, but I am always returned:
AttributeError: type object 'By' has no attribute 'cssSelector'
Or something similar. I'm clearly missing some documentation somewhere, because I can't figure out why ID is a valid attritube for By and cssSelector isn't. What am I missing?
You want to use By.CSS_SELECTOR.
For your reference, here are the attributes available for the By class:
ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With