无法使用Java和Selenium通过部分链接文本查找元素

时间:2019-01-15 16:48:22

标签: java selenium selenium-webdriver xpath webdriverwait

使用geckodriver 0.23.0,firefox 64.0.2,硒3.12,java 8我无法通过部分链接文本找到该元素。不使用框架。链接文本为“ 帐户(1)”。页面“ 查看所有帐户

中只有一个相同文本的实例

html:

<li>    
      <a href="/accounting/view_all_accounts?_t=039f18daf35b4a00f0093dd17aa70730be385f6f&amp;to_render=account" class="first accounting_page_menu  ">Accounts (1)</a>
      <ul>
        <li>
          <a href="/accounting/details?_t=e3d4ea94f5ed862d95196a620f1147be13b02979&amp;to_render=account" class="first accounting_page_menu ">Primary</a>
        </li>

        <li>
        <a onclick="javascript: ModalUtil.loadEditableModal('/accounting/details_new_account', false, false, true);" class="add-accounts">Add New Account...</a>
        </li>
        <li>
        <a href="/accounting/view_all_accounts?_t=039f18daf35b4a00f0093dd17aa70730be385f6f&amp;to_render=account" class="first accounting_page_menu ">View All Accounts</a>
        </li>
      </ul>
  </li>

我用于查找元素的代码:“帐户(n)”,其中n = 1、2、3 ...

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

我尝试使用“ 帐户”和“ 帐户(”),它们都返回未找到的相同404-没有此类元素错误

控制台日志:

1547499923019   webdriver::server   DEBUG   -> POST /session/bed7e7d2-d849-4bd0-ab17-fdca3fb080f9/element {
  "value": "Accounts ",
  "using": "partial link text"
}
1547499923020   Marionette  TRACE   0 -> [0,315,"WebDriver:FindElement",{"using":"partial link text","value":"Accounts "}]
1547499923241   Marionette  TRACE   0 <- [1,315,{"error":"no such element","message":"Unable to locate element: Accounts ","stacktrace":"WebDriverError@chrome://mario ... entError@chrome://marionette/content/error.js:388:5\nelement.find/</<@chrome://marionette/content/element.js:339:16\n"},null]
1547499923240   webdriver::server   DEBUG   <- 404 Not Found {"value":{"error":"no such element","message":"Unable to locate element: Accounts ","stacktrace":"WebDriverError@chrome://marionette/content/error.js:178:5\nNoSuchElementError@chrome://marionette/content/error.js:388:5\nelement.find/</<@chrome://marionette/content/element.js:339:16\n"}}

1 个答案:

答案 0 :(得分:0)

正如您所提到的,您正在尝试查找文本为 Accounts(n)的元素,其中n = 1、2、3 ...,以及另外两个具有 linkText < / em>,因为存在添加新帐户查看所有帐户,而不是使用partialLinkText,最好使用 XPath 您可以使用以下解决方案:

  • XPath

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//li/a[@class='first accounting_page_menu' and starts-with(@href,'/accounting/view_all_accounts?')][starts-with(.,'Accounts')]"))).click();
    

更新

根据讨论Official locator strategies for the webdriver部分链接文本选择器 XPath选择器更为可取。但是,根据此用例,由于存在相似的链接文本,因此构造 XPath 会更容易。