如果两个 类 具有相同的类名,如何引用第二个类名 - 使用 selenium webdriver

How to refer second classname if two classes have same classname - using selenium webdriver

我想从第二个“109-top-dark-grey-block ng-binding”获取文本(现在是空的,但将来会得到一些文本,所以现在打印空应该没问题) class。尝试过的 tabIndex 和 nth-child 都不起作用。 “

<div class="122-top-section-btm-half">
    <div class="108-top-grey-m12x3"></div>
    <div class="109-top-dark-grey-block ng-binding">ab ab xyz</div>
</div>

” “

<div class="d122-top-section-btm-half">
    <div class="108-top-grey-m12x4"></div>
    <div class="109-top-dark-grey-block ng-binding"></div>

更新

要获取第二个 div 块的文本 nth-child 应该可行。我在 chrome 工具中本地测试了选择器:

所以在你的 Java:

String elementText = driver.findElement(By.cssSelector(".d122-top-section-btm-half:nth-child(2) .ng-binding")).getText();

应该可以解决问题 - 因为 CSS spec says nth-child is 1 indexed - 不是 0 - 所以它是第二个 child。

旧答案

根据您提供的 HTML 片段,您可以使用 CSS 选择器。所以你可以这样做:

String elementText = driver.findElement(By.cssSelector(".d122-top-section-btm-half .109-top-dark-grey-block")).getText();

或者,如果您在第一个 div 中紧跟在带有 ng-binding 的元素之后,那么它会更干净:

String elementText = driver.findElement(By.cssSelector(".d122-top-section-btm-half .ng-binding")).getText();

两者都会 return 元素文本 - 也许可以查看 CSS Selectors Guide 以了解更多信息。