简体   繁体   中英

How fetch first element from json list in selenium java?

I have following list of ids in json format. I want to access first id in selenium using java. I tried using

String item = driver.findElement(By.xpath("//ul//li[1]")).getText(); 

but didn't help.

 <body>
   <div id="json">
       <span class="collapser"></span>
         {
            <ul class="obj collapsible">
               <li>
                 <span class="prop" title="<root>.hdps">
                   <span class="q">"</span>
                  hdps
                   <span class="q">"</span>
                 </span>
                :
                <span class="collapser"></span>
                 [
                    <ul class="array collapsible">
                          <li>
                              <span class="num">65085</span>
                                  ,
                          </li>
                          <li>
                              <span class="num">65089</span>
                                   ,
                          </li>
                          <li>
                              <span class="num">65711</span>
                                   ,
                          </li>

                      </ul>
                      ]
               </li>
     </ul>
 }
 </div>

What i understand is you are trying to read the value of ID attribute of an element. I am really not sure the intent of your question . But this how you can get to the value of ID.

  • You will need to get reference to the element using one of the various element locators. In this case, you have leveraged By.xpath() . You can validate the correctness of the XPATH used by Firefox Xpath checker. Once you use correct XPATH , you will get reference of webElement .

     WebElement wElement = driver.findElement(By.xpath("//ul//li[1]")); // validate the correct XPATH using available tools - ex : firefox xpath checker etc. 
  • You will need to get the value of id attribute of the element.

     String requiredID = wElement.getAttribute("id"); 

Let me know if this works.

As pendem answered that, you can get first ID as you want by using xpath. But here I found that the xpath which you have used find 2 elements as there are two ul elements having li . If you use xpath having specific ul with class attribute as - .//ul[@ class="array collapsible"]//li[1] will work.

If you have provided all the relevant HTML, it should be as simple as the below.

String id = driver.findElement(By.cssSelector("span.num")).getText();

This just returns the first instance of the IDs.

If that doesn't work, you'll have to do some more digging, eg is this in an IFRAME or is it a timing issue or ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM