如何通过文本识别元素?

How to identify an element through text?

我正在尝试使用 Selenium 做一些基本的事情,并且我正在尝试通过 "Text" 查找元素,因为我的所有元素都是动态生成的,或者它们具有共同的属性名称和值。

我想在下面div到达"SelTest",这里是一个街区:

 <div ng-mouseenter="hover=true" ng-mouseleave="hover=false" class="object workspace" ng-repeat="workspace in workspaces | filter:{'workspace_title':workspaceFilter, 'is_archived':false} | orderBy: 'workspace_title'" ui-sref="main.workspace({workspaceId: workspace.id})" href="#!/workspace/a43d95fa24acbfc4757ba86a4d8dec22">
            <i class="mdi mdi-folder"></i>
            <div class="title">SelTest</div>
            <div class="desc"></div>
            <div class="tools ng-hide" ng-show="hover" style="">
                <button type="button" ng-click="workspace.toggleArchive();$event.stopPropagation();" class="btn btn-default btn-xs">
                    <span>Archive</span>
                </button>
            </div>
        </div>

而其余代码具有完全相同的属性名称和值。

这是更大的图景:

有没有办法去SelTest

要将带有文本的元素定位为 SelTest,您需要为 visibilityOfElementLocated() 引入 WebDriverWait,您可以使用以下

  • cssSelector:

    WebElement ele = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.object.workspace[ng-repeat^='workspace in workspaces'][href*='workspace'] div.title")));
    
  • xpath:

    WebElement ele = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='object workspace' and starts-with(@ng-repeat, 'workspace in workspaces')][contains(@href, 'workspace')]//div[@class='title' and text()='SelTest']")));