我有点击,有一个长,生成的类不唯一使用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>
谁能告诉我怎么一下就可以或许指出了一个错误我在以前的选择了什么?谢谢。
你可以试试下面的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()]"
通过浏览器建议的默认的XPath的工作:
xpath = "//*[@id=\'react-app-root\']/div/div/div[2]/div/div[1]/button[2]"
但如果有人有更好看的解决方案,我仍然对此表示赞赏。
这似乎是一个完美的使用情况下的data attribute。
该属性可以用来唯一标识测试按钮,将更加适应你的UI结构的变化。
所需的元件是一个动态元素,以便以找到具有诱导WebDriverWait为元素是可点击的元件并且可以使用下列的解决方案:
cssSelector
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[class^='styled__ShareButton-sc-'] span"))).click();
xpath
:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class]//span[text()='Add to favourites']"))).click();