有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

html Selenium Java如何搜索和查找给定父元素的特定嵌套元素是相同的

假设我有一个这样的页面:

<div class = "A">
   <h1>AA</h1>
   <p>This</p>
</div>

<div class = "A">
   <h1>BB</h1>
   <p>This</p>
</div>

假设这种情况持续到可变长度,那么每次加载页面时,都会有一个随机数目的“class a”div,其顺序为h1为:“CC”,“DD”,等等。。。如何查找并单击div中带有“BB”的链接“This”这就是我尝试过的:

driver.findElement(By.xpath("//*[text()='BB']")).findElement(By.xpath("//*
[text()='This']")).click();

我也尝试过:

WebElement name = driver.findElement(By.xpath("//*[text()='BB']"));
name.findElement(By.xpath("//*[text()='This']")).click();

但在这两种情况下,我总是在div中点击带有“AA”的“This”我可以将其定义为单击第二个div,但如果下次我加载页面时,它会随机化顺序,以便第一个div和第二个div切换。在这种情况下,将其硬编码为始终单击第二个元素将不起作用

因此,我想知道如果满足条件“BB”存在,如何在div中搜索


共 (3) 个答案

  1. # 1 楼答案

    这个想法是:

    • 获取列表中所有“A”类元素
    • 查找包含“BB”的标题文本
    • 如果是这样的话,那么获取该类“A”索引的标记p
    • 点击“这个”

    下面是这项技术的完整实现

    List<WebElement> allClass = driver.findElements(By.className("A"));
        String optionString = "BB"; 
    
        for(WebElement elm : allClass){
            WebElement header = elm.findElement(By.tagName("h1"));
            if(header.getText().equalsIgnoreCase(optionString)){
                WebElement thisP = elm.findElement(By.tagName("p"));
                thisP.click();
                break;
            }
        }
    
  2. # 2 楼答案

    要查找并单击带有BB的div中的链接This,可以使用以下代码块:

    driver.findElement(By.xpath("//div[@class='A']/h1[text()='BB']//following::p[1]")).click();
    
  3. # 3 楼答案

    试试这个xpath

    //div[@class='A']//h1[text()='BB']//following::p
    

    或者

    //div[contains(@class,'A')]//h1[text()='BB']//following::p
    

    代码:

    WebElement thisClick= driver.findElement(By.xpath("//div[contains(@class,'A')]//h1[text()='BB']//following::p"));
    thisClick.findElement(By.xpath("p[text()=='This']")).click();