【问题标题】:Can't locate a button using selenium to press on it找不到使用 selenium 按下的按钮
【发布时间】:2020-06-18 08:03:40
【问题描述】:

我在 python 中创建了一个脚本,使用 selenium 点击webpage 中的like button。我使用 xpath 来定位该按钮,并且我认为我已经正确使用了它。但是,脚本似乎没有找到该按钮,因此它会抛出 TimeoutException 错误,指向包含 xpath 的行。

由于无法在不登录的情况下点击该按钮,因此我希望脚本能够将相关的 html 连接到该按钮,以便我了解我可以正确找到它。

我试过了:

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

如何使用 selenium 找到显示为 heart symbol 的 like 按钮?

【问题讨论】:

  • 注意 svg 标签

标签: python python-3.x selenium xpath web-scraping


【解决方案1】:

点击Like按钮诱导WebDriverWait()并等待visibility_of_element_located()及以下xpath。

然后将元素滚动到视图中并单击。

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

【讨论】:

    【解决方案2】:

    你可以这样做

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

    likeBtn 等于 likeSVG div 的父级,因为您可以使用类似于 CLI 中的文件导航命令的 XPATH。

    【讨论】:

    • 您的解决方案正在运行@Lucan。除非我得到任何与 xpath 相关的解决方案,否则我肯定会去做。它肯定值得加分。谢谢。
    【解决方案3】:

    尝试使用.find_element_by_xpath(xPath) 方法(使用完整的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()
    

    【讨论】:

    • 对不起@Xiddoc,我不在absolute xpath 之后,我可以在检查元素时直接复制它。我正在尝试创建一个相对的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多