[英]How to find a element with specific text in <span> with Selenium
I'm using Selenium WebDriver. 我正在使用Selenium WebDriver。 I'm facing issue with dynamically changing ID.
我面临着动态更改ID的问题。 I've gone through some post such as Handle elements that have changing ids all the time through Selenium Webdriver but didn't found a solution that can help me.
我看过一些文章,例如Handle元素,这些元素通过Selenium Webdriver一直在更改id,但是没有找到可以帮助我的解决方案。
Including start-with
and contains
in XPath can't help as there are plenty of elements which start with similar text and id keep changing. 在XPath中包括
start-with
和contains
会无济于事,因为有很多以相似的文本和id开头的元素会不断变化。 Please refer the HTML
below for more clarity. 请参考下面的
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>
mat-option-
. mat-option-
开头的元素很少。 <span>
. <span>
的文本。 I tried driver.findElement(By.xpath(".//span[contains(text(), 'Campaign Details']"));
but not working for me. 我尝试过
driver.findElement(By.xpath(".//span[contains(text(), 'Campaign Details']"));
但对我不起作用。
按照您提供的HTML来标识带有文本作为Campaign Details的元素,因为该元素是Angular元素,您必须诱使WebDriverWait使该元素可见 ,如下所示:
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')]")));
The only unique this is the text in <span>
So the text is : Campaign Details 唯一唯一的是
<span>
的文本,因此文本是: Campaign Details
WebElement campaignDeatils = driver.findElement(By.xpath("//i[text()='description']/following-sibling::span[text()='Campaign Details']"))
campaignDeatils.getText(); // or any other operation you wanna do.
WebElement campaignDeatils = driver.findElement(By.xpath(""//i[@class='fa fa-bullhorn']/following-sibling::span[text()='Campaigns']"))
campaignDeatils.getText();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.