Home > Net >  Selenium: Can't find element by class name in any way
Selenium: Can't find element by class name in any way

Time:10-28

I have this problem where I can't access a button trough it's class name in any way I could think of. This is the HTML:

<button >
 
 <faceplate-number pretty="" number="18591"><!---->18.591</faceplate-number> weitere Kommentare anzeigen
 
 </button>

I tried to access it using:

driver.find_element(By.CLASS_NAME, "expand-button")

But the error tells me that there was no such element. I also tried X-Path and Css-Selector which both didn't appear to work.

I would be glad for any help!
Kind Regards and Thanks in advance
Eirik

CodePudding user response:

It could be because you check before the element is created in the DOM.

one way to solve this problem is by using the waites option like below

driver.implicitly_wait(10)
driver.get("http://somedomain/url_that_delays_loading")
my_dynamic_element = driver.find_element(By.ID, "myDynamicElement")

You can read more about it here: https://www.selenium.dev/documentation/webdriver/waits/#implicit-wait

Another way is by using the Fluent Wait whhich marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.

#Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
#Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
#Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
#Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)
#specify the condition to wait on.
wait.until(ExpectedConditions.element_to_be_selected(your_element_here));

you can also read more about that from the official documentation https://www.selenium.dev/documentation/webdriver/waits/#fluentwait

  • Related