Link to home
Start Free TrialLog in
Avatar of Rodric MacOliver
Rodric MacOliverFlag for New Zealand

asked on

How to count the number of options in a select DOM Element in Java

Hi folks is there a way to count the number of options in a select DOM Element retrieved using JSoup or Java by itself after having the file saved in a text file?
Any help with this would be appreciated.
Cheers!
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

'Elements' is essentially a List, so the size() method can be used if you reverse the 'serialization' process
Avatar of Rodric MacOliver

ASKER

How would I go about using the size function?
How would I go about using the size function?
If I try
"System.out.print(chapters.size());"
I get 0 even though I was supposed to get 16...
You'd have to show me that in context
CEHJ, here is the code I'm using for you to have a look:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;


public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ffNumber = new javax.swing.JTextField();
        receiveTitle = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Check Title");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(receiveTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ffNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)))
                .addContainerGap(294, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ffNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(receiveTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(336, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    public static String html2text(String html) {
                return Jsoup.parse(html).text();
            }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            int storyId = Integer.parseInt(ffNumber.getText());
            String address = "https://www.mysite.com/9475375/1/";
            Document doc = Jsoup.connect(address).get();
            String title = doc.title();
            String text = doc.body().text();
            Elements info = doc.select("div#storycontent");            
            
            //Receive Chapters from Jump Menu?????
            Elements chapters = doc.select("#jump");
            System.out.print(chapters.size());//not working!!!!!!
                   
            File file = new File("./"+storyId+".txt");
            
            if (!file.exists()) {
				file.createNewFile();
			}
                        //The true below is to indicate that the Append should be used
                        String content = info.toString();
                        content = html2text(content);
			FileWriter fw = new FileWriter(file.getAbsoluteFile());//add,true before last parenteses to adicionar ao final
			BufferedWriter bw = new BufferedWriter(fw);
                        //bw.write(info.toString());
			bw.write(content);                        
			bw.close();
 
			System.out.println();
                        receiveTitle.setText(title+" Done");
                        
            
        } catch (IOException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField ffNumber;
    private javax.swing.JButton jButton1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JLabel receiveTitle;
    // End of variables declaration                   
}

Open in new window

Cheers!
I'd need to test that but i can't connect to that URL
Its not online yet, I'm just using on a local server...

The select would be something like the following if that helps...

<select name="jump" id="jump" onchange="var c = this.selectedIndex; if(c > 0) self.location = '/s/5957714/'+c+'/'"><option selected="selected" value="0">Jump:</option><option value="1">Chapter 1</option><option value="2">Chapter 2</option><option value="3">Chapter 3</option><option value="4">Chapter 4</option><option value="5">Chapter 5</option><option value="6">Chapter 6</option><option value="7">Chapter 7</option><option value="8">Chapter 8</option><option value="9">Chapter 9</option><option value="10">Chapter 10</option><option value="11">Chapter 11</option><option value="12">Chapter 12</option><option value="13">Chapter 13</option><option value="14">Chapter 14</option><option value="15">Chapter 15</option><option value="16">Chapter 16</option><option value="17">Chapter 17</option><option value="18">Chapter 18</option><option value="19">Chapter 19</option><option value="20">Chapter 20</option><option value="21">Chapter 21</option><option value="22">Chapter 22</option><option value="23">Chapter 23</option><option value="24">Chapter 24</option><option value="25">Chapter 25</option><option value="26">Chapter 26</option><option value="27">Chapter 27</option><option value="28">Chapter 28</option><option value="29">Chapter 29</option><option value="30">Chapter 30</option><option value="31">Chapter 31</option><option value="32">Chapter 32</option><option value="33">Chapter 33</option><option value="34">Chapter 34</option><option value="35">Chapter 35</option><option value="36">Chapter 36</option><option value="37">Chapter 37</option><option value="38">Chapter 38</option><option value="39">Chapter 39</option><option value="40">Chapter 40</option><option value="41">Chapter 41</option><option value="42">Chapter 42</option><option value="43">Chapter 43</option><option value="44">Chapter 44</option><option value="45">Chapter 45</option><option value="46">Chapter 46</option><option value="47">Chapter 47</option><option value="48">Chapter 48</option><option value="49">Chapter 49</option><option value="50">Chapter 50</option></select>

Open in new window

select#jump would be the key then, not #jump
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial