【问题标题】:Unable to locate the button or link using either xpath, id, name or css selector无法使用 xpath、id、名称或 css 选择器找到按钮或链接
【发布时间】:2019-04-16 13:15:24
【问题描述】:

无法使用 id/name/xpath/CSSSelector 定位元素

尝试了以下代码,但都没有给出响应

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\'form\']/p/button/span")));
driver.findElement(By.xpath("//*[@id=\'form\']/p/button/span")).click();

WebElement checkout = driver.findElement(By.xpath("//[@id=\'form\']/p/button/span"));
checkout.click();

HTML

 <button type="submit" name="processCarrier" class="button btn btn-default standard-checkout button-medium" style="">
    <span> Proceed to checkout <i class="icon-chevron-right right"></i> </span>
 </button>

【问题讨论】:

  • HTML:
  • 也许该元素在 iframe 内,而 webdriver 不在该 iframe 内。查找任何 iframe,如果元素在其中,则执行 driver.switchTo().frame("frame_id_or_index_goes_here")
  • 有什么答案可以解决您的问题吗?如果是,那么请通过单击答案投票计数下方的勾号来接受答案。所以它可以对其他人有所帮助。如果不是,请使用更多详细信息更新您的问题,或随时在 cmets 中提问。谢谢:)

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

尝试使用 CSS 选择器。

WebElement checkout = driver.findElement(By.cssSelector("button.standard-checkout span"));
checkout .click();

或者你可以使用 WebDriverWait 和 Css Selector。

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.standard-checkout span")));
element.click()

【讨论】:

    【解决方案2】:

    您可能会得到org.openqa.selenium.InvalidSelectorException,因为您应该在// 之后使用* 来匹配任何具有id=form 或特定标签名称的节点(标签)。

    改成//*[@id='form']/p/button/span

    或者使用更具体的like

    xpath : //button[@name='processCarrier'] 等效 CSS : button[name='processCarrier']

    并使用隐式/显式等待使元素在 DOM 中可用以执行操作。

    【讨论】:

      【解决方案3】:

      假设您将在 &lt;button&gt; 元素上调用 click(),因此您需要诱导 WebDriverWait 以使所需的元素可点击,您可以使用以下Locator Strategies

      • cssSelector:

        new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.standard-checkout.button-medium[name='processCarrier']>span"))).click();
        
      • xpath:

        new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='button btn btn-default standard-checkout button-medium' and @name='processCarrier']/span"))).click();
        

      【讨论】:

        猜你喜欢
        • 2015-04-28
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 2021-12-21
        相关资源
        最近更新 更多