【问题标题】:How to locate a button inside an article tag using Selenium through Java如何通过 Java 使用 Selenium 在文章标签内定位按钮
【发布时间】:2019-06-10 19:30:43
【问题描述】:

我无法在以下代码的文章中检测到按钮:

<article id="ride-f6ba24ca-d847-44b7-987e-81db6e6dee47" class="DetailPage__container--1VLdd"><div class="DetailPage__highlights--1uyrQ"><section></section><form aria-label="Offer highlights" class="DetailPage__section--qtXxV"><button type="submit"><span>Accept offer</span></button></form></div></article>

我试试:

driver.findElement(By.xpath("//*[text()='Details']"))
driver.findElement(By.xpath("//button[.//span[text()='Accept offer']]"))

没有运气

我无法在 java 中检测到元素 Accept offer with selenium

【问题讨论】:

  • 在一个框架中?动态加载(所以你需要等待)?这些是通常的罪魁祸首......

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

所需元素是一个动态元素,因此要定位您必须为 elementToBeClickable() 诱导 WebDriverWait 的元素,您可以使用以下任一 Locator Strategies

  • cssSelector:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("article[class^='DetailPage__container--'][id^='ride-']>div[class^='DetailPage__highlights--'] button[type='submit']>span")));
    
  • xpath:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//article[starts-with(@class, 'DetailPage__container--') and starts-with(@id, 'ride-')]/div[starts-with(@class, 'DetailPage__highlights--')]//button[@type='submit']/span[text()='Accept offer']")));
    

【讨论】:

  • 感谢您的回答 DebanjanB 我已经尝试使用 WebDriverWait 但没有运气,但我尝试使用 findElement(By.xpath("//button[.//span[text( )='接受报价']]"))。这是我的错吗?
  • 无论如何我试试你的解决方案,我会尽快告诉你
  • 你的方法抛出 TimeException 并且它不工作
【解决方案2】:

最后你的方法适用于下面的方法

private void waitForElement(By by, long delay) {
    LocalDateTime end = LocalDateTime.now().plusSeconds(delay);
    while (LocalDateTime.now().compareTo(end) <= 0) {
        if (driver.findElements(by).size() > 0) {
            break;
        }
    }
}

我先运行方法等待,然后检查是否有一个包含以下元素的列表

if (driver.findElements(By.xpath("//article[starts-with(@class, 'DetailPage__container--') and starts-with(@id, 'ride-')]/div[starts-with(@class, 'DetailPage__highlights--')]//button[@type='submit']/span[text()='Accept offer']")).size() > 0){//Here i call the element}

所以如果元素存在,我可以在里面调用它,如果没有时间异常更多

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2015-06-24
    • 2019-09-01
    • 2021-10-13
    • 2020-02-03
    相关资源
    最近更新 更多