硒 WebDriver 无法通过链接文本查找元素

2022-09-04 06:53:11

我正在尝试选择一个包含锚点的元素,但文本被埋在div内的段落中。以下是我正在使用的HTML:

<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
    <p>
    <strong class="ng-binding">Smoke Sequential</strong>
    </p>

我用来尝试捕获它的代码是针对“Smoke Sequential”文本的:

driver.findElement(By.linkText(service)).click();

其中变量“服务”包含“Smoke Sequential”。当我运行它时,我得到以下错误:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Smoke Sequential"}

任何帮助将不胜感激。


答案 1

问题可能出在html的其余部分,即您没有发布的部分。

在这个例子中(我刚刚关闭了打开的标签):

<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
    <p>
    <strong class="ng-binding">Smoke Sequential</strong>
    </p>
    </div>
</div>
</a>

我能够毫无困难地找到该元素:

driver.findElement(By.linkText("Smoke Sequential")).click();

如果元素中有更多的文本,您可以尝试按部分链接文本查找:

driver.findElement(By.partialLinkText("Sequential")).click();

答案 2

使用 xpath 和 text()

driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));