在网页上查找xpath或类似的东西(=identifier)



我正试图点击视频中的某个位置。我已经用xpath尝试过了,但没有成功。

例如,在这个tiktok视频中:https://www.tiktok.com/@willsmith/video/71254844820328926510?is_from_webapp=v1&item_id=7125844820328926510&web_id=7139992072584676869

我正试着用硒(蟒蛇(点击心脏。这是我的代码:

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()

上面写着";无法定位元素";。我不知道为什么。我甚至在代码中添加了一些睡眠,因为我认为网站没有完全加载,甚至没有尝试使用不同的xpath。我还试着用";心脏位置";但如果我检查元素,ID就很难理解。有人能帮帮我吗?提前感谢!

  1. 您需要使用正确的定位器
  2. 并等待元素可点击
    对于前一个WebDriverWait预期条件,应使用显式等待
    以下代码有效:(如果您已经登录(
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:webdriverschromedriver.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()

如果您想使用XPath而不是CSS Selector,只需使用更改上面的行即可

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

最新更新