我正在使用 Selenium WebDriver。我面临动态更改 ID 的问题。我浏览过一些帖子,例如 Handle elements that have changing ids all the time through Selenium Webdriver但没有找到可以帮助我的解决方案。
包括start-with
和contains
在 XPath 中无济于事,因为有很多元素以相似的文本开头,并且 id 不断变化。请引用HTML
为了更清楚起见,请参见下文。
<mat-option _ngcontent-c1="" class="__mat-option mat-option ng-star-inserted"
role="option" tabindex="0" id="mat-option-4"
aria-selected="false" aria-disabled="false">
<span class="mat-option-text">
<i _ngcontent-c1="" class="material-icons">description</i>
<span _ngcontent-c1="" style="padding-left: 8px">Campaign Details</span>
</span>
<div class="mat-option-ripple mat-ripple" mat-ripple=""></div>
</mat-option>
- 请注意上面 HTML 中的 ID,它是动态的并且不断变化。
- 像这样具有相同类名的元素很少。
- 还有一些以
mat-option-
开头的元素. - 唯一独特的是
<span>
中的文本.
我试过driver.findElement(By.xpath(".//span[contains(text(), 'Campaign Details']"));
但不适合我。
最佳答案
根据您提供的 HTML 来标识带有文本作为广告 Activity 详细信息的元素,因为该元素是 Angular 元素,您必须诱导 WebDriverWait em> 使元素可见如下:
WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//mat-option[@class='__mat-option mat-option ng-star-inserted' and @role='option'][starts-with(@id,'mat-option-')]/span[@class='mat-option-text']//span[contains(.,'Campaign Details')]")));
关于java - 如何使用 Selenium 在 <span> 中查找具有特定文本的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641101/