Home > Software design >  How To find elements in html by condition using selenium in java?
How To find elements in html by condition using selenium in java?

Time:04-17

I'm try to find two type of elements : td , img
and i tried using Xpath and cssSelector as i want to find td , td/img i use like this

driver.findElements(By.cssSelector("td"))

and try

driver.findElements(By.xpath("//*[self::td|self::img]"))

but when using first one, i couldn't get img elements

List<String> list = new ArrayList<String>();  
    for(WebElement element : driver.findElements(By.cssSelector("td")))
    {
        if(element.getText().equals("img") == true) 
        {
            String tr = "img";
            list.add(tr);
        }
        else 
        {
            list.add(element.getText());            
        }
    }
                

and second one is not working well.

HTML code look like this.

<div id="bodyContent">
 <form name ="lessonForm" method="post">
  <div id="listBox">
   <div >
    <dl >
     <dd>
      <div class ="cont">
      <table class = "board">
       <thead> ... </thead>
        <tbody>
         <tr class ="odd-row">
            <td class ="first"></td>
            <td> offline </td>
            <td>  2022-03-02 </td>
        </tbody>
       </table>
      </div>
      :: after 
     </dd>
    </dl>
   </div>
  </div>
  
<div id="listBox">
   <div >
    <dl >
     <dd>
      <div class ="cont">
      <table class = "board">
       <thead> ... </thead>
        <tbody>
         <tr class ="odd-row">
            <td class ="first"></td>
            <td> offline </td>
            <td>  2022-03-09 </td>
            <td>   
                <img src ="on_full.gif">  
            </td>
              
        </tbody>
       </table>
      </div>
      :: after 
     </dd>
    </dl>
   </div>
  </div>
  
 

how can i add that img and td elements in List ? It's just whether it's an img or not
I wish I could bring a letter. to know what is this img.

I'm waiting for your help. Thank u for read this.

CodePudding user response:

Whichever locator strategy you are using, be it CSS, xPath, etc. You should always make sure that these locators are unique in HTML-DOM.

Steps to check if they are unique or not:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath/css and see, if your desired element is getting highlighted with 1/1 matching node.

Also alone td is not a valid CSS, replace it with //td and make a valid xpath.

Code:

    List<String> list = new ArrayList<String>();  
    for(WebElement element : driver.findElements(By.xpath("//td")))
    {
        if(element.findElements(By.xpath(".//img")).size() > 0) 
        {
            String tr = "img";
            list.add(tr);
        }
        else 
        {
            list.add(element.getText());            
        }
    }
  • Related