如何点击一个按钮,没有任何独特的类属性

问题描述 投票:1回答:4

我有点击,有一个长,生成的类不唯一使用XPath选择按钮的麻烦。它有2种嵌套元素 - SVG和跨度。我不知道我是否应该寻找这个按钮使用它们或许通过类的前瞻性和例如选择第二个选项。

我尝试了以下选择:

xpath = "//button[contains(@class, 'styled_ShareButton')](1)" 
xpath = "//button span[contains('Add to favorites')]"
xpath = "//button[contains(@span, 'fa-heart')]"
xpath = "//svg[contains(@class, 'fa-heart')]"

但他们没有工作。

下面是我很感兴趣的按钮(这是同一类的2个按钮2日)

<button class="styled__ShareButton-sc-1jdjzg3-3 feqRzW Button-sc-1emfup8-0 kFlIhg">
<svg aria-hidden="true" data-prefix="far" data-icon="heart" class="svg-inline--fa fa-heart fa-w-16 " role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor"></path></svg>
<span>Add to favourites</span>
</button>

谁能告诉我怎么一下就可以或许指出了一个错误我在以前的选择了什么?谢谢。

java selenium xpath css-selectors webdriverwait
4个回答
0
投票

你可以试试下面的XPath:

xPath = "//span[contains(text(), 'Add to favourites')]//parent::button"

要么

xPath = "(//*[@id='react-app-root']//button[contains(@class, 'styled__ShareButton')])[last()]"

要么

xPath = "//*[@id='react-app-root']//span[contains(text(), 'Add to favourites')]//parent::button"

要么

xPath = "(//*[@id='react-app-root']//button[contains(@class, 'styled__ShareButton')])[2]"

要么

xPath = "(//button[contains(@class, 'styled__ShareButton')])[2]"

要么

xPath = "(//button[contains(@class, 'styled__ShareButton')])[last()]"

0
投票

通过浏览器建议的默认的XPath的工作:

xpath = "//*[@id=\'react-app-root\']/div/div/div[2]/div/div[1]/button[2]"

但如果有人有更好看的解决方案,我仍然对此表示赞赏。


0
投票

这似乎是一个完美的使用情况下的data attribute

该属性可以用来唯一标识测试按钮,将更加适应你的UI结构的变化。


0
投票

所需的元件是一个动态元素,以便以找到具有诱导WebDriverWait为元素是可点击的元件并且可以使用下列的解决方案:

  • cssSelectornew WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[class^='styled__ShareButton-sc-'] span"))).click();
  • xpathnew WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class]//span[text()='Add to favourites']"))).click();
© www.soinside.com 2019 - 2024. All rights reserved.