有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在类中定位特定按钮。该按钮可能与该类之外的其他按钮共享类名

这是具有classname操作的按钮。我怎么能只指向这个snackbar类中的这个按钮呢。我需要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>

共 (3) 个答案

  1. # 1 楼答案

    如果你想得到按钮,它是^{}标记的子元素,而^{} attribute包含snackbar-pos,你可以使用以下表达式:

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

    演示:

    enter image description here

    然而,坚持这一点可能更有意义:

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

    甚至这个Jerry Rocker文本:

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

    参考资料:

  2. # 2 楼答案

    您可以使用下面给定的xpath

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

    希望这能有所帮助

  3. # 3 楼答案

    假设您打算点击按钮,文本为SHOW,与文本为的元素关联,为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();