2

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" class="_8-yf5 " color="#262626" fill="#262626" height="24" role="img" viewBox="0 0 24 24" width="24">

Any help is appreciated.

BikGer2
  • 68
  • 1
  • 8

2 Answers2

6

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']
Anand Gautam
  • 2,018
  • 1
  • 3
  • 8
  • I appreciate the help. So, I've tried it, and it is in fact not the only svg tag in the html. It clicks on something else. Is there any way I could search it by the aria-label="Messenger"? – BikGer2 Feb 17 '22 at 17:56
  • More DOM lines are to be investigated. Basically you have to traverse through a good unique locator down to this svg to have it work. Another way is to identify with multiple attributes, like `//*[name()='svg' and @aria-label='Messenger']` – Anand Gautam Feb 17 '22 at 18:08
  • Props to you man, it works. I really appreciate it. I'm relatively new to building bots and I don't know xpath expressions. Either way, I really appreciate it! – BikGer2 Feb 17 '22 at 19:25
1

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:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • I really appreciate the help man! Using just //*[name()='svg' and @aria-label='Messenger'] worked. – BikGer2 Feb 17 '22 at 19:27
  • 1
    @BikGer2 It isn't just the xpath but the [_`CSS_SELECTOR`_](https://stackoverflow.com/a/48578370/7429447) and [WebDriverWait](https://stackoverflow.com/a/52607451/7429447) will be inevitable for you in the long run. – undetected Selenium Feb 17 '22 at 19:32
  • Alright, I'll take some time to read about it. Thanks for the advice! – BikGer2 Feb 17 '22 at 19:49