robots.txt
robots.txt

Reputation: 149

Can't locate a button using selenium to press on it

I've created a script in python using selenium to click on a like button available in a webpage. I've used xpath in order to locate that button and I think I've used it correctly. However, the script doesn't seem to find that button and as a results it throws TimeoutException error pointing at the very line containing the xpath.

As it is not possible to hit that like button without logging in, I expect the script to get the relevant html connected to that button so that I understand I could locate it correctly.

I've tried with:

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

link = "https://www.instagram.com/p/CBi_eIuAwbG/"

with webdriver.Chrome() as driver:
    wait = WebDriverWait(driver,10)

    driver.get(link)
    item = wait.until(EC.visibility_of_element_located((By.XPATH,"//button[./svg[@aria-label='Like']]")))
    print(item.get_attribute("innerHTML"))

How can I locate that like button visible as heart symbol using selenium?

Upvotes: 1

Views: 162

Answers (3)

KunduK
KunduK

Reputation: 33384

To click on Like Button induce WebDriverWait() and wait for visibility_of_element_located() and below xpath.

Then scroll the element into view and click.

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


driver.get("https://www.instagram.com/p/CBi_eIuAwbG/")
element=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//button[.//*[name()='svg' and @aria-label='Like']]")))
element.location_once_scrolled_into_view
element.click()

Upvotes: 1

Lucan
Lucan

Reputation: 3635

You can do it like this

likeSVG = driver.find_element(By.CSS_SELECTOR, 'svg[aria-label="Like"]')
likeBtn = likeSVG.find_element(By.XPATH, './..')
likeBtn.click()

likeBtn is equal to the parent of the likeSVG div as you can use XPATH similar to file navigation commands in a CLI.

Upvotes: 1

Xiddoc
Xiddoc

Reputation: 3638

Try using the .find_element_by_xpath(xPath) method (Uses full xpath):

likeXPATH = "/html/body/div[1]/section/main/div/div[1]/article/div[2]/section[1]/span[1]/button"

likeElement = driver.find_element_by_xpath(likeXPATH)

likeElement.click()

Upvotes: -1

Related Questions