在Selenium中查找具有多个div的元素

时间:2016-09-12 12:50:25

标签: selenium xpath selenium-webdriver css-selectors

我试图找到一个像占位符一样的元素。我会将其他元素拖放到此处。 HTML

<div class="value1" > <div class="value2" data-id="some_number" data-aura+"value"> 
<div class="place holder"> div2, div3 > Add component </div>

<div class="row contentPanel" data-aura-render="53:56;a"><div class="col-lg-12" data-aura-rendered-by="54:56;a">
<div class="interactions siteforceDesignTimeRegion" data-region-name="content" data-allow-drop="true" data-item-id="87f9712-27f4-564-9445-fg30cf4321a7" data-aura-render="6:56;a" data-aura-class="siteforceDesignTimeRegion">
<div class="Placeholder siteRegion" data-aura-render="10:56;a" data-aura-class="forceDesignTimeEmptyRegion">Add components to this place</div>
<!--render facet: 18:56;a--></div></div></div>

我在我的代码中尝试过以下内容。它实际上在控制台中工作。但是当我在代码中使用它时它不起作用。如果有人用cssselector或xpath提供答案会很有帮助。感谢。

driver.findElement(By.xpath("//div[contains(@class, 'row contentPanel')]"));

1 个答案:

答案 0 :(得分:2)

来自评论: -

  

它抛出此错误..org.openqa.selenium.NoSuchElementException:没有这样的元素:无法找到元素:

exception可能有如下原因: -

  • 可能在您要查找元素时,它不会出现在DOM上,因此您应该实现WebDriverWait等待元素出现在DOM上下面: -

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement el = wait.until(ExpectedConditions.presenceOf‌​ElementLocated(By.cs‌​sSelector("div.row.c‌​ontentPanel")));
    
  • 可能此元素位于任何frame/iframe内。如果是,则需要在找到所需元素之前切换frame/iframe,如下所示: -

    WebDriverWait wait = new WebDriverWait(driver, 10);
    
    //Wait until frame/iframe to available and then switch to it
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name"));
    
    //Now find the desired element 
    WebElement el = wait.until(ExpectedConditions.presenceOf‌​ElementLocated(By.cs‌​sSelector("div.row.c‌​ontentPanel")));
    
    //Once all your stuff done with this frame/iframe need to switch back to default for further stuff
    driver.switchTo().defaultContent();