如何根据使用 Selenium 的 html 从使用 xpath 找到的元素中检索属性 aria-label 的值

ben*_*ben 4 python selenium webdriver getattribute selenium-webdriver

我有以下 HTML 跨度:

<button class="coreSpriteHeartOpen oF4XW dCJp8">
    <span class="glyphsSpriteHeart__filled__24__red_5 u-__7" aria-label="Unlike"></span>
</button>
Run Code Online (Sandbox Code Playgroud)

我也有一个webElement表示包含这个跨度的按钮,我使用xpath. 如何aria-label从元素中检索值(Unlike)?

我试图做:

btn = drive.find_element(By.xpath, "xpath") 
btn.get_attribute("aria-label")
Run Code Online (Sandbox Code Playgroud)

但它什么都不返回。如何从元素对象中检索具有“aria-label”属性的元素的文本值?

Ser*_*ers 8

aria-label是 span 元素的属性,而不是按钮。你可以这样得到它:

btn = drive.find_element(By.xpath, "xpath") 
aria_label = btn.find_element_by_css_selector('span').get_attribute("aria-label")
Run Code Online (Sandbox Code Playgroud)

或者,如果您的目标是找到 span 包含属性的按钮aria-label="Unlike"

btn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"]]')
#you can add class to xpath also if you need
btn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"] and contains(@class,"coreSpriteHeartOpen)]')
Run Code Online (Sandbox Code Playgroud)


Deb*_*anB 0

根据您的问题和您共享的HTML,该元素似乎是一个React元素,因此要检索属性aria-label,您必须引入WebDriverWait才能使所需元素可见,您可以使用以下解决方案:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "element_xpath_you_found"))).get_attribute("aria-label"))
Run Code Online (Sandbox Code Playgroud)

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Run Code Online (Sandbox Code Playgroud)