【问题标题】:How to locate a specific button inside a class. The button might share classname with other button outside this class如何在类中定位特定按钮。该按钮可能与该类之外的其他按钮共享类名
【发布时间】:2019-12-28 17:12:32
【问题描述】:

这是带有类名操作的按钮。我怎样才能只指向这个快餐栏类中的这个按钮。我需要 xpath。

<div class="snackbar-container  snackbar-pos bottom-center" style="width: 475px; background: rgb(50, 50, 50); opacity: 1;" xpath="1">
   <p style="margin: 0px; padding: 0px; color: rgb(255, 255, 255); font-size: 14px; font-weight: 300; line-height: 1em;">Show similar patients for  Jerry Rocker</p>
   <button class="action" style="color: rgb(76, 175, 80);">SHOW</button>
</div>

试过这个。 网页元素

snackbarButton=driver.findElement(By.xpath("//button[contains(@class,'action') and contains(@class,'snackbar-pos']"));

    <div class="snackbar-container  snackbar-pos bottom-center" style="width: 475px; background: rgb(50, 50, 50); opacity: 1;" xpath="1">
       <p style="margin: 0px; padding: 0px; color: rgb(255, 255, 255); font-size: 14px; font-weight: 300; line-height: 1em;">Show similar patients for  Jerry Rocker</p>
       <button class="action" style="color: rgb(76, 175, 80);">SHOW</button>
    </div>

【问题讨论】:

  • 您好,欢迎来到 stackoverflow。这个问题确实需要您要查找的html示例。请阅读the article 了解一个最小的、可重现的示例

标签: java selenium xpath webdriverwait xpath-1.0


【解决方案1】:

大概你打算点击文本为 SHOW 的按钮与文本为 Showsimilar patients for Jerry Rocker 的元素相关联,并实现你诱导 WebDriverWait 使 元素可点击,您可以使用以下任一Locator Strategies:

  • xpath1:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//p[text()='Show similar patients for  Jerry Rocker']//following::button[1]"))).click();
    
  • xpath2:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//p[text()='Show similar patients for  Jerry Rocker']//following::button[@class='action' and text()='SHOW']"))).click();
    

【讨论】:

    【解决方案2】:

    如果您想获取属于&lt;div&gt; 子标签的按钮,其中class attribute 包含snackbar-pos,您可以使用以下表达式:

    //div[contains(@class,'snackbar-pos')]/button
    

    演示:

    但是,坚持xpath attribute 可能更有意义:

    //div[@xpath='1']/button
    

    甚至这个Jerry Rocker文字:

    //p[contains(text(),'Jerry Rocker')]/following-sibling::button
    

    参考资料:

    【讨论】:

      【解决方案3】:

      你可以使用下面给定的 xpath。

      //div[@class='snackbar-container  snackbar-pos bottom-center']//child::p//following-sibling::button[@class='action']
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 2012-10-06
        • 2020-12-22
        • 1970-01-01
        • 2016-08-26
        • 2013-05-04
        • 1970-01-01
        相关资源
        最近更新 更多