brad
brad

Reputation: 878

How to identify the nested element using Selenium and Python

I have a nested element possibly within <svg> that I can't seems to access

I tried using

driver.find_element(By.CSS_SELECTOR, 'button.login-fake-btn')

and

driver.find_element(By.CSS_SELECTOR, 'login-fake-btn')

and a few others.

HTML structure of nested svg:

<svg class="1">
<div id="2">
<div>
<div class="3">
<div class="4">
<li>
<button class="5" type="button" id="login-fake-btn">
...closing tags

Snapshot of HTML:

HTML

I have no success with xpath either.

Error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"button.login-fake-btn"}

How do I get to a nested svg using a css selector (or xpath, but I understand css to be better)?

Upvotes: 0

Views: 2460

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

It's a <button> element and it's out of the <svg> tag and possibly moving forward you'd invoke click() on it. Hence to locate the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.login-btn.btn-shadow#login-fake-btn[data-testid='login-fake-btn']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='login-btn btn-shadow' and @id='login-fake-btn'][@data-testid='login-fake-btn']")))
    
  • Note : You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

References

You can find a couple of relevant discussions on NoSuchElementException in:

Upvotes: 1

Related Questions