Home > Net >  How to find svg element with selenium?
How to find svg element with selenium?

Time:02-18

I'm building a python Instagram bot, and I'm trying to get it to click on the DMs icon, but I'm not sure how to select it.

I tried selecting by Xpath, but I can't seem to be able to navigate it to the icon. Here's Instagram's html code for the DMs icon:

<svg aria-label="Messenger"  color="#262626" fill="#262626" height="24" role="img" viewBox="0 0 24 24" width="24">

Any help is appreciated.

CodePudding user response:

You have to apply a slightly different locator strategy to find svg.

Here is what works:

driver.find_element(By.XPATH, "//*[name()='svg']")

assuming that this is the only svg element (as provided in your query)

Combination of more than one attribute from the same DOM line:

//*[name()='svg' and @aria-label='Messenger']

CodePudding user response:

The desired element is a element so to click() on 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:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[aria-label='Messenger']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg' and @aria-label='Messenger']"))).click()
    
  • 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 interacting with SVG element in:

  • Related