How to get all text from different elements under one div

孤人 提交于 2021-02-05 07:51:32

问题


I have problem, here is html pseudocode:

<div class="content" id="ui6" role ="tabpanel">
 <p> text </p>
 <ul> <li> text2 </li>
      <li> text3 </li>
 </ul>
  </div>

I want to get text, text2 and text3 and print them, but I can only manage to get "text".

Here is the code:

List<WebElement> sectionThreeText = driver.findElements(By.cssSelector("#ui6"));
    for(WebElement e : sectionThreeText) {
        System.out.println(e.getText());
    }

I tried also find it by:

css = "#ui6 > p ul"
xpath = "//*[@id=ui6]"
xpath = "//*[@id=ui6]/*"
xpath = "//*[@id=ui6]/p | //*[@id=ui6]/ul"

I am out of ideas. Where I make mistake?


回答1:


To print text, text2 and text3 you can use either of the following Locator Strategies:

  • cssSelector:

    System.out.println(driver.findElement(By.cssSelector("div.content#ui6")).getText());
    
  • xpath:

    System.out.println(driver.findElement(By.xpath("//div[@class='content' and @id='ui6']")).getText());
    

As an alternative you can also use the following Locator Strategies:

  • To print text:

    • cssSelector:

      System.out.println(driver.findElement(By.cssSelector("div.content#ui6>p")).getText());
      
    • xpath:

      System.out.println(driver.findElement(By.xpath("//div[@class='content' and @id='ui6']/p")).getText());
      
  • To print text2:

    • cssSelector:

      System.out.println(driver.findElement(By.cssSelector("div.content#ui6 ul>li")).getText());
      
    • xpath:

      System.out.println(driver.findElement(By.xpath("//div[@class='content' and @id='ui6']//ul/li")).getText());
      
  • To print text3:

    • cssSelector:

      System.out.println(driver.findElement(By.cssSelector("div.content#ui6 ul li:nth-child(2)")).getText());
      
    • xpath:

      System.out.println(driver.findElement(By.xpath("//div[@class='content' and @id='ui6']//ul//following-sibling::li[2]")).getText());
      



回答2:


Using the Jsoup you can retrive the HTML page

    Document doc = Jsoup.parse(htmlString);
    Elements divs = doc.select("div");
    for(Element elem : divs){
      System.out.println(elem.html()); //get all elements inside div
    }



回答3:


To get text2 and text3 use xpath //*[@id="ui6"]/ul/li not xpath = "//*[@id=ui6]/p | //*[@id=ui6]/ul" as you have mentioned. //*[@id="ui6"]/ul/li This xpath will help get all li elements inside ul




回答4:


You can get all descendants of the ui6 element with xpath(".//*").

Try this:

WebElement sectionThreeText = driver.findElement(By.cssSelector("#ui6"));
List<WebElement> childs = sectionThreeText.findElements(By.xpath(".//*"));
for(WebElement e: childs )
{
    System.out.print(e.getText());
}


来源:https://stackoverflow.com/questions/59245555/how-to-get-all-text-from-different-elements-under-one-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!