【问题标题】:How to click on the element as per the HTML which is within a modal box through Selenium?如何通过 Selenium 根据模态框中的 HTML 单击元素?
【发布时间】:2018-09-18 06:26:52
【问题描述】:

我正在自动化一些需要注销的网站。我在这段代码中遇到了困难:

WebDriverWait wait = new WebDriverWait(d, 10);
WebElement Category_Body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("user logout")));
Category_Body.click();
d.findElement(By.id("logout_user")).click();
Thread.sleep(1000);

HTML:

<a class="user logout" title="Sign out" data-target="#confirm_popup" data-toggle="modal"></a>

错误:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"user logout"}

【问题讨论】:

  • iframe 吗?
  • 我也尝试了不同的方法来解决这个错误。不工作,请分享您的观点。
  • @NarendraR 它不在 iframe 中
  • 使用 By.class('user') 或 By.cssSelector('.user.logout')
  • @DakshinamurthyKarra 对不起,这也不起作用

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

尝试以下代码:

WebDriverWait wait = new WebDriverWait(d, 10);
WebElement Category_Body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".user.logout")));
Category_Body.click();

PS:你也可以使用ExpectedCondition.elementToBeClickable 来做到这一点。

希望对你有帮助!

【讨论】:

    【解决方案2】:

    我认为问题出在标识符上 你用过

        WebElement Category_Body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("user logout")));
    

    但是根据你的 HTML

    <a class="user logout" title="Sign out" data-target="#confirm_popup" data-toggle="modal"></a>
    

    该链接没有名为“用户注销”的 ID 不使用 id 尝试使用 class By.findElementByClassName("user logout")

    作为第二种解决方案,尝试使用 xpath(大多数情况下都可以)

    如果两种解决方案都不可用,您可以使用 JavascriptExecutor(难以捕获的元素可以使用 JavascriptExecutor 轻松处理)

    注意:主要问题是您在没有此类 ID 时使用“用户注销”

    干杯

    【讨论】:

    • By.class("user logout") 搜索具有“用户注销”类的元素,而不是具有“用户”和“注销”类的元素。
    • 抱歉应该是 By.findElementByClassName("user logout")
    • 我尝试了绝对和动态 xpath ,类仍然无法正常工作
    • 可能是等待时间不够。尝试将等待时间增加到大约 60 秒。 (不确定它是否会起作用)您是如何提取 XPath 的? (如果您有 IDE,您可以使用它来识别元素的不同选择器)
    • 当一个属性类被赋予一个值“用户注销”时——该元素被认为有两个类——“用户”和“注销”。不是一个单一的类名“用户注销”。
    【解决方案3】:

    根据您在 Model Box 中将所需元素定位到 logout,您需要为 元素诱导 WebDriverWait可点击,您可以使用以下任一选项:

    • cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.user.logout[title='Sign out'][data-toggle='modal']"))).click();
      
    • xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='user logout' and @title='Sign out'][@data-toggle='modal']"))).click();
      

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 2019-02-15
      • 2020-07-28
      相关资源
      最近更新 更多