【问题标题】:How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium如何根据使用 Selenium 的 html 从使用 xpath 找到的元素中检索属性 aria-label 的值
【发布时间】:2019-01-31 05:57:20
【问题描述】:

我有以下 HTML 跨度:

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

我还有一个webElement 代表包含我使用xpath 找到的这个跨度的按钮。如何从元素中检索 aria-label 值(Unlike)?

我尝试过:

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

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

【问题讨论】:

  • 您能否发布一个更完整的代码/文档示例,其中包含包含按钮和在 Python 中创建 btn 的代码?
  • 现在够了吗?
  • 这有帮助,但是您是如何启动驱动程序的?我应该链接minimal, complete and verifiable example,否则我需要对您的代码做出可能不准确的假设。即便如此,"xpath" 对我来说还是一个非常可疑的 xpath。
  • 分享你使用的 xpath 定位器
  • 您能否向我解释一下 Instagram js 如何检测您单击了哪个点赞按钮,因为在一个页面中有多个具有相同类名的点赞按钮?

标签: python selenium selenium-webdriver webdriver getattribute


【解决方案1】:

以下在 Java 中为我工作,

WebElement btnelement= driver.findElement(
                        By.xpath("//span[@aria-label='Unlike']"));
System.out.println("Attribute value is " + btnelement.getAttribute("value"));

【讨论】:

    【解决方案2】:
    # 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() 
    

    我改用了这些方法,效果很好!

    【讨论】:

      【解决方案3】:

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

      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)]')
      

      【讨论】:

        【解决方案4】:

        根据您的问题和您共享的 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
        

        【讨论】: