5

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.

2 Answers 2

10

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']
Sign up to request clarification or add additional context in comments.

3 Comments

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"?
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']
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!
2

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:

3 Comments

I really appreciate the help man! Using just //*[name()='svg' and @aria-label='Messenger'] worked.
@BikGer2 It isn't just the xpath but the CSS_SELECTOR and WebDriverWait will be inevitable for you in the long run.
Alright, I'll take some time to read about it. Thanks for the advice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.