如何在`量角器'中定位动态元素

时间:2016-02-04 02:56:18

标签: javascript jquery html angularjs protractor

当我尝试运行以下代码时出现此错误:

  

失败:元素不可见

以下是我想要找到的元素的html代码:

<a class="dropdown-toggle ng-binding ng-scope" aria-expanded="false"    
role="button" href="/" data-toggle="dropdown" ng-if="tab.subtabs">
Content
<span class="caret"></span></a>
<ul class="dropdown-menu ng-scope" role="menu" ng-if="tab.subtabs">
<li class="ng-scope" ng-repeat="test in tab.subtabs">
<a class="ng-binding" target="_self" href="/custom/ui">Custom</a>
</li>
<li class="ng-scope" ng-repeat="test in tab.subtabs">
<a class="ng-binding" target="_self" href="/patch/ui">Patch</a></li>
<li class="ng-scope" ng-repeat="test in tab.subtabs">
<a class="ng-binding" target="_self" href="/swd/ui">Software</a>

我想点击标签中的元素:

<a class="ng-binding" target="_self" href="/custom/ui">Custom</a>
<a class="ng-binding" target="_self" href="/patch/ui">Patch</a>
<a class="ng-binding" target="_self" href="/swd/ui">Software</a>

我已尝试在protractor中使用以下代码,但它无效:

it("should click on Content and then custom", function(){
    element(by.xpath('/html/body/bf-header/div/nav/div/div/div[2]/ul[1]  
   /li[2]/a')).element(by.xpath('/html/body/bf-header/div/nav/div/div   
   /div[2]/ul[1]/li[3]/ul/li[1]')).click();

1 个答案:

答案 0 :(得分:2)

  

element(by.xpath('/html/body/bf-header/div/nav/div/div/div[2]/ul[1]
/li[2]/a')).element(by.xpath('/html/body/bf-header/div/nav/div/div
/div[2]/ul[1]/li[3]/ul/li[1]')).click();

好吧,现在您可以看到为什么Protractor Style Guide建议不要使用XPath定位技术:

  

永远不要使用xpath

     

为什么?

     
      
  • 它是所有
  • 中最慢和最脆弱的定位策略   
  • 标记是   很容易变化,因此xpath定位器需要一个   很多维护
  •   
  • xpath表达式不可读且很难   调试
  •   

并非总是如此,如果你选择XPath,你所做的表达式必须至少真的简单易读。要修复的第一件事是,如果你要继续使用XPath,那就不是制作绝对的XPath表达式 - 你不必从html元素开始,并检查从树下到目标的每一个元素元件。

在这种情况下,简单&#34;通过链接文本&#34;或者&#34;通过部分链接文本&#34;定位器应该完美地工作:

element(by.linkText("Custom")).click();

请注意,可能会抛出Failed: element not visible错误,因为在尝试单击子菜单之前,请不要单击菜单将其打开(假设这些是您需要单击的子菜单链接)。

您可能还需要等待元素可点击

var EC = protractor.ExpectedConditions;
var custom = element(by.linkText("Custom"));

browser.wait(Ec.elementToBeClickable(custom), 5000);
custom.click();

希望有所帮助。

相关问题