【问题标题】:How to identify an element through classname and click on it using Selenium and Java?如何通过类名识别元素并使用 Selenium 和 Java 点击它?
【发布时间】:2019-08-14 06:11:43
【问题描述】:

通过类单击按钮,因为它没有 ID 。还是通过价值?

尝试了 className 、 cssSelector 、 partialLinkText 和 LinkText 但遗憾的是单击保存按钮不起作用

System.out.println("Succesful in Saving Product ");
WebElement save = driver.findElement(By.className("bttn-positive save-button"));
save.click();

应该可以点击保存按钮

【问题讨论】:

  • 任一元素不可交互或弹出僵局错误
  • 你能把html sn-p贴出来吗?
  • 您使用的定位器无效。发布 html 和错误消息。

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

我们不能在className 定位器中使用多个类名。因此,您可以使用具有多个类名的 XPath 定位器,如下所示 (//input[@class='bttn-positive save-button'])

代码:

System.out.println("Succesful in Saving Product ");
WebElement save = driver.findElement(By.xpath("//input[@class='bttn-positive save-button']"));
save.click();

【讨论】:

    【解决方案2】:

    您在使用driver.findElement(By.className("bttn-positive save-button")) 时不能传递多个类名,这样做您将面临Invalid selector: Compound class names not permitted 错误。

    到绿色按钮上的click(),文本为Save,您必须为elementToBeClickable() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

    • cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.bttn-positive[value^='Save'][type='button']"))).click();
      
    • xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(@class, 'bttn-positive') and starts-with(@value, 'Save')][@type='button']"))).click();
      

    【讨论】:

      【解决方案3】:

      试试 save.submit();

      提交按钮用于将整个表单提交到服务器。我们可以像上面所做的那样在 web 元素上使用 click() 方法,就像普通按钮一样,或者在表单中的任何 web 元素或提交按钮本身上使用 submit() 方法。

      【讨论】:

      【解决方案4】:

      在这种情况下,“save.click()”会起作用,但有些时候将任何产品保存在任何应用程序(如电子商务或银行域)上,它将无法正常工作,更重要的是认为 click() 会导致新页面load,此方法将尝试加载页面。因此,如果当前元素是表单,则最好使用“save.submit()”,或者在表单中使用 this 将被提交。根据您的要求,提交 () 一个是更好的选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-28
        • 1970-01-01
        • 1970-01-01
        • 2020-09-20
        • 1970-01-01
        • 2019-09-01
        • 2019-05-10
        • 1970-01-01
        相关资源
        最近更新 更多