无法使用XPath,ID,名称或CSS选择器找到按钮或链接

时间:2019-04-16 13:15:25

标签: java selenium xpath css-selectors webdriverwait

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

尝试了以下代码,但均未给出响应

class FooController {
    public function summary(Foo $foo, SerializerInterface $serialzer)
    {
        $context = SerializationContext::create()->setGroups('summary');
        $data = $serialzer->serialize($foo, json, $context);

        return new JsonResponse($data);
    }

    public function details(Foo $foo, SerializerInterface $serialzer)
    {
        $context = SerializationContext::create()->setGroups('details');
        $data = $serialzer->serialize($foo, json, $context);

        return new JsonResponse($data);
    }
}

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

HTML

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

3 个答案:

答案 0 :(得分:0)

尝试使用CSS选择器。

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

或者您可以使用WebDriverWait和CSS选择器。

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

答案 1 :(得分:0)

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

将其更改为//*[@id='form']/p/button/span

或更具体地使用

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

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

答案 2 :(得分:0)

大概您将在click()元素上调用<button>,因此您需要诱使 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();