Solved Get code between...?

Discussion in 'Plugin Development' started by Meatiex, Jul 21, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    Meatiex

    How would I get "100%", 96% ect... from the below string?
    HTML:
     <div id ="class1">100%<div>
    <div id ="class2">96%<div>
    <div id ="class3">82%<div>
    <div id ="class4">100%<div>
    Code I used to grab this from my website.
    Code:
              URL url = new URL("http://markstuff.net/grades");
              URLConnection con = url.openConnection();
              InputStream in = con.getInputStream();
              String encoding = con.getContentEncoding();
              encoding = encoding == null ? "UTF-8" : encoding;
             
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              byte[] buf = new byte[8192];
              int len = 0;
              while ((len = in.read(buf)) != -1) {
                  baos.write(buf, 0, len);
              }
              String body = new String(baos.toByteArray(), encoding);
              System.out.println(body);
     
  2. May not be the best code but it should work:
    string = string.substring(string.indexOf(">", string.length - 5);
     
  3. @Meatiex
    Pseudo method would be to split the String using line separator, and splitting those Strings with > and <.
    Code:
    String[] lines = body.split(System.lineSeparator());
    
    for(String line : lines) {
        String percent = line.split(">")[1].split("<")[0];
    }
    However, for proper HTML parsing, I use Jsoup.
     
    Meatiex likes this.
  4. Offline

    Meatiex

    Thank you so much! It works great! :D
    Code:
              for(String line : lines) {
                  if (line.contains("%")) {
                  String percent = line.split("=\"")[1].split("<div>")[0].replace("\">", " ");
                  System.out.println(percent);
                  }
              }
    It returns:
    Code:
    class1 100%
    class2 96%
    class3 82%
    class4 100%
     
    Assist likes this.
Thread Status:
Not open for further replies.

Share This Page