如何在课程内找到特定的按钮。该按钮可能与该类之外的其他按钮共享类名

时间:2019-08-23 11:15:46

标签: java selenium xpath webdriverwait xpath-1.0

这是具有类名操作的按钮。我如何只指向小吃店类中的此按钮。我需要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>

试过了。 WebElement

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 个答案:

答案 0 :(得分:0)

大概您打算单击文本为 SHOW 的按钮,并将其与文本为 Show Jerry Rocker的类似患者的元素相关联,以实现诱使< em> 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();
    

答案 1 :(得分:0)

如果您要获取的按钮是<div>包含snackbar-pos的{​​{3}}标记的子代,则可以使用以下表达式:

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

演示:

class attribute

但是,坚持使用此enter image description here可能更有意义:

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

甚至是这个Jerry Rocker文本:

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

参考文献:

答案 2 :(得分:0)

您可以在下面给定的xpath中使用。

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

希望这会有所帮助。