简体   繁体   English

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

[英]How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium

I have the following HTML span: 我有以下HTML范围:

<button class="coreSpriteHeartOpen oF4XW dCJp8">
    <span class="glyphsSpriteHeart__filled__24__red_5 u-__7" aria-label="Unlike"></span>
</button>

I also have a webElement representing the button containing this span that I have found using xpath . 我也有一个webElement表示包含使用xpath找到的该范围的按钮。 How can I retrieve the aria-label value (Unlike) from the element? 如何从元素检索aria-label值(与其他不同)?

I tried to do: 我试着做:

btn = drive.find_element(By.xpath, "xpath") 
btn.get_attribute("aria-label")

but it returns nothing. 但它什么也没返回。 How to retrieve the text value of an element with 'aria-label' attribute from the element object? 如何从元素对象中检索具有'aria-label'属性的元素的文本值?

aria-label is attribute of span element, not button. aria-label是span元素的属性,而不是button。 You can get it like this: 您可以这样获得:

btn = drive.find_element(By.xpath, "xpath") 
aria_label = btn.find_element_by_css_selector('span').get_attribute("aria-label")

Or if your goal is to find button with span contains attribute aria-label="Unlike" : 或者,如果您的目标是查找跨度包含属性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)]')

As per your question and the HTML you have shared it seems that the element is a React element, so to retrieve the attribute aria-label you have to induve WebDriverWait for the desired element to be visible and you can use the following solution: 根据您的问题和您共享的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"))

Note : You have to add the following imports : 注意 :您必须添加以下导入:

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

I used these methods instead and it worked! 我改用这些方法,而且行得通!

Following worked for me in Java, 在我为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM