![](/img/trans.png)
[英]Using aria-label to locate and click an element with Python3 and Selenium
[英]How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium
我有以下HTML范围:
<button class="coreSpriteHeartOpen oF4XW dCJp8">
<span class="glyphsSpriteHeart__filled__24__red_5 u-__7" aria-label="Unlike"></span>
</button>
我也有一个webElement
表示包含使用xpath
找到的该范围的按钮。 如何从元素检索aria-label
值(与其他不同)?
我试着做:
btn = drive.find_element(By.xpath, "xpath")
btn.get_attribute("aria-label")
但它什么也没返回。 如何从元素对象中检索具有'aria-label'属性的元素的文本值?
aria-label
是span元素的属性,而不是button。 您可以这样获得:
btn = drive.find_element(By.xpath, "xpath")
aria_label = btn.find_element_by_css_selector('span').get_attribute("aria-label")
或者,如果您的目标是查找跨度包含属性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)]')
根据您的问题和您共享的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"))
注意 :您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Like method
lov = el.find_element_by_class_name('glyphsSpriteHeart__outline__24__grey_9').click()
# Unlike method
lov = el.find_element_by_class_name('glyphsSpriteHeart__filled__24__red_5').click()
我改用这些方法,而且行得通!
在我为Java工作之后,
WebElement btnelement= driver.findElement(
By.xpath("//span[@aria-label='Unlike']"));
System.out.println("Attribute value is " + btnelement.getAttribute("value"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.