【问题标题】:FInd specific element in selenium python在 selenium python 中查找特定元素
【发布时间】:2021-10-12 00:42:02
【问题描述】:

我正在尝试让我的使用 selenium 的程序在此 html 代码上查找(然后单击):

<svg aria-label="Add Photo or Video" class="_8-yf5 " color="#262626" fill="#262626" height="24" role="img" viewBox="0 0 48 48" width="24"></svg>

我会使用什么函数来找到这个特定的元素? 谢谢

【问题讨论】:

标签: python selenium webdriver


【解决方案1】:

这是一个 svg 网页元素。您可以像这样定位(通过 xpath):

//*[name()='svg' and @aria-label='Add Photo or Video']

在 Selenium 中基本上有 4 种点击方式。

我将使用这个 xpath

//*[name()='svg' and @aria-label='Add Photo or Video']

代码试用 1:

time.sleep(5)
driver.find_element_by_xpath("//*[name()='svg' and @aria-label='Add Photo or Video']").click()

代码试用 2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg' and @aria-label='Add Photo or Video']"))).click()

代码试用 3:

time.sleep(5)
button = driver.find_element_by_xpath("//*[name()='svg' and @aria-label='Add Photo or Video']")
driver.execute_script("arguments[0].click();", button)

代码试用 4:

time.sleep(5)
button = driver.find_element_by_xpath("//*[name()='svg' and @aria-label='Add Photo or Video']")
ActionChains(driver).move_to_element(button).click().perform()

进口:

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

PS:如果我们在HTML DOM 中有唯一条目,请检查dev tools(谷歌浏览器)。

检查步骤:

Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到高亮 987654335@匹配节点。

【讨论】:

    【解决方案2】:

    请使用这个 xpath

    yourEle = driver.find_element_by_xpath("(//svg[@aria-label='Add Photo or Video'])")
    

    【讨论】:

    • 这给了我一条错误消息:消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"(//svg[@aria-label= '添加照片或视频'])"}
    • 你是在加载之前访问元素,请在点击/某事之前添加等待时间
    • 根据 Cruisepandey 等待逻辑:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg' and @aria-label= '添加照片或视频']"))).click()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2022-01-27
    • 2020-01-13
    相关资源
    最近更新 更多