-1

so far I have the following code:

like_button =  driver.find_element_by_xpath('//div[@class="QBdPU "]/*[name()="svg"][@aria-label="Like"]')
like_button().click()

To correspond with the following HTML (I'm trying to click the svg section): enter image description here

Was wondering if anyone could correct my xpath.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
v0lk
  • 58
  • 1
  • 6
  • 1
    you may actually want to target the – pcalkins Oct 19 '20 at 23:38
  • `svg` node is not a *child* of `div`, but a *descendant*, so either replace `.../*[name()="svg"]` with `...//*[name()="svg"]` or add `.../span/...` between them as in [Jack Fleeting answer](https://stackoverflow.com/questions/64436417/what-is-the-correct-xpath-for-the-svg-in-the-html-featured-in-this-example/64436456#64436456) – JaSON Oct 20 '20 at 06:50

3 Answers3

1

Try changing your xpath expression to

//div[@class="QBdPU "]/span/*[name()="svg" and @aria-label="Like"]

and see if it works.

JaSON
  • 4,843
  • 2
  • 8
  • 15
Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
0

As kjhughes mentioned in the comment, svg elements are in different namespaces of HTML, so we need to be careful when picking it via xpath.

I see that you're trying to get Like button on Instagram, I've tested this on Chrome, I think it will work on Selenium as well. Try:

//*[name()="svg" and @aria-label="Like" and @height="24"]

Remove and @height="24" if you also want to get Like button on comments. Like button on comment has and @height="12" attribute.

jackblk
  • 1,076
  • 8
  • 19
0

To identify and click() on the Like button on Instagram you can use either of the following Locator Strategies:

  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//button[@type='button']//span//*[name()="svg" and @aria-label='Like']"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='button'] span > svg[aria-label="Like"]"))).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
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352