Home > Software engineering >  Selenium on find_element
Selenium on find_element

Time:10-15

I tried with find_element_by() and I noticed that 3.5 Selenium version changed to find_element syntax but there are two ways: find_element(By.ID, "id-name") and find_element("id", "id-name") which one is the correct way? It worked the 2nd way but first one didn't. What do I have to consider to use one?

CodePudding user response:

Both are correct

By.ID is literally an attribute with a string value of 'id'

BY.ID is better to use just in case they change this in the future, so you do not have to update your code.

CodePudding user response:

If you want to use the first option (at least that's what I understand from your question) you need to import By:

from selenium.webdriver.common.by import By

And then you can locate elements like:

element = browser.find_element(By.ID, "id-name")

It is however advisable to always wait for elements to load, so you may also want to import:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

And too try and locate elements like so:

element = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler")))

Selenium documentation can be found here: https://www.selenium.dev/documentation/

  • Related