首页 > 解决方案 > 无法根据以下锚标记定位元素

问题描述

请告知如何在以下代码中找到新业务标签的链接。我已经尝试了以下 xpath,但它没有工作:

driver.findElement(By.linkText("NEW BUSINESS")).click
driver.findElement(By.xpath("//span[@class='hdBottomBar']/a[1]"))

HTML:

<span class="hdBottomBar">
                <a class="hdTopBar" href="javascript: void navCntl('NewBusiness','NavBar');" onmouseover="window.status='New Business';return true" onmouseout="window.status='';return true" name="newBusiness">NEW BUSINESS</a>

标签: javaselenium-webdriverxpathcss-selectorswebdriverwait

解决方案


该元素是启用了JavaScript的元素,因此要调用click()您必须诱导WebDriverWait以使该元素可点击,并且您可以使用以下任一解决方案:

  • linkText

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("NEW BUSINESS"))).click();
    
  • cssSelector

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("span.hdBottomBar>a.hdTopBar[name='newBusiness']"))).click();
    
  • xpath

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[@class='hdBottomBar']/a[@class='hdTopBar' and @name='newBusiness'][text()='NEW BUSINESS']"))).click();
    

推荐阅读