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

Question:

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 class="expand-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

Asked By: eirikg

||

Answers:

Possible issue 1

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

Possible issue 2

it is also possible that the element might be partially or completely blocked by an element overlaying it. If that is the case, then you will have to dismiss the overlaying element before you will be able to perform any action on your target

Answered By: DilanTsasi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.