【问题标题】:find title of empty Div in Table Row - Selenium Java在表行中查找空 Div 的标题 - Selenium Java
【发布时间】:2015-11-01 19:05:45
【问题描述】:

此表行中有一个 Div 类和标题经常更改。当它读取特定内容时,我需要捕获 div。

代码如下:

<tr class="this_row">
<td class="something"></td>
<td></td>
<td></td>
<td></td>
<td>
    <div class="i_need_this" title="or This"></div>
</td>
</td></td>
<td class="blah"></td>

等等

现在我的代码如下所示:

findElement(By.xpath("//tr[contains(@class, 'this_row')//div[contains(@class, 'i_need_this')]")).getText().contains("This text matches exactly within td class=blah from above"))

这不起作用。

有什么建议吗?

【问题讨论】:

    标签: java selenium xpath selenium-webdriver css-selectors


    【解决方案1】:

    这听起来像是 WebDriverWait 和预期条件的显式等待的工作:

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement td = wait.until(ExpectedConditions.textToBePresentInElement(By.cssSelector("tr.this_row td.blah"), "This text matches exactly within td class=blah from above"));
    

    在这里,我们正在等待最多 10 秒,让 This text matches exactly within td class=blah from above 文本出现在 td 元素内,类 blahtr 元素内,类 this_row

    或者,我们也可以等待特定的div 元素出现

    WebElement div = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("tr.this_row > td > div")));
    System.out.println(div.getAttribute("title"));
    

    【讨论】:

    • 我确实有一个实例,其中 "or this" 在 "tr.this_row > td > div" 中,但仍然报告找不到 Title ... 有没有更广泛的方法?也许在“tr.this_row > td > div”中发现的多个“or this”实例混淆了它?它只找到最上面的实例吗?谢谢!
    • 如何找到最底部的 tr.this_row 实例?谢谢!!
    • @Zodzie 尝试tr.this_row:last-of-type &gt; td &gt; div css 选择器
    【解决方案2】:

    这对我有用。

    public static void test() throws InterruptedException {
        if (driver.findElement(By.cssSelector("tr.this_row > td > div")).getAttribute("title").contains("or This")){testFollows();}
        else {System.out.print("title not found \n");}
    }
        public static void testFollows() throws InterruptedException {
            if (driver.findElement(By.cssSelector("tr.this_row")).getText().contains("This text matches exactly within td class=blah from above"))
            {JOptionPane.showMessageDialog(null, "Found Target");} 
            else {System.out.print("found nothing2 \n");}
        }
    

    如果没有 alecxe 的回答,就无法做到。

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多