Home > Blockchain >  Find xpath or something similar (=identifier) on web page
Find xpath or something similar (=identifier) on web page

Time:09-06

I am trying to click on a place on a video. I tried it with xpath already, but without success.

For example on this tiktok video: https://www.tiktok.com/@willsmith/video/7125844820328926510?is_from_webapp=v1&item_id=7125844820328926510&web_id=7139992072584676869

I'm trying to click on the heart with selenium (python). That's my code:

    if driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[2]/div[1]/div[3]/div[1]/div[1]/div[3]/button[1]/span/div/svg/g/path") :
    driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[2]/div[1]/div[3]/div[1]/div[1]/div[3]/button[1]/span/div/svg/g/path").click()

It says that it's "Unable to locate element". I don't know why. I even added some sleep to the code because I thought that the website didn't load up fully or even tried with a different xpath. I also tried to do it with the ID of the "heart-location" but the ID is very hard to understand if I inspect element. Could someone please help me out? Thanks in advance!

CodePudding user response:

  1. You need to use the correct locator
  2. And to wait for the element to be clickable.
    For the former WebDriverWait Expected Conditions explicit wait should be used.
    The below code works: (In case you are already logged in)
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
url = "https://www.tiktok.com/@willsmith/video/7125844820328926510?is_from_webapp=v1&item_id=7125844820328926510&web_id=7139992072584676869"

driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[data-e2e='like-icon']"))).click()

In case you want to use XPath instead of CSS Selector just change the line above with

wait.until(EC.element_to_be_clickable((By.XPATH, "//span[@data-e2e='like-icon']"))).click()

  • Related