Advertisement
Guest User

ContentURL

a guest
Apr 22nd, 2022
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. import org.jsoup.Jsoup;
  2. import org.jsoup.nodes.Document;
  3. import org.jsoup.nodes.Element;
  4.  
  5. public class ContentURL
  6. {
  7.     private final String _url;
  8.     private final String _select;
  9.     private boolean _next = false;
  10.    
  11.     public ContentURL(String url)
  12.     {
  13.         this(url, "");
  14.     }
  15.    
  16.     public ContentURL(String url, String select)
  17.     {
  18.         _url = url;
  19.         _select = select;
  20.     }
  21.    
  22.     public ContentURL next()
  23.     {
  24.         _next = true;
  25.         return this;
  26.     }
  27.    
  28.     private String result()
  29.     {
  30.         try
  31.         {
  32.             final Document doc = Jsoup.connect(_url).ignoreContentType(true).ignoreHttpErrors(true).get();
  33.             if (_select.isEmpty())
  34.                 return doc.html();
  35.            
  36.             final Element element = doc.selectFirst(_select);
  37.             if (_next)
  38.                 return element.nextSibling().toString();
  39.            
  40.             return element.text();
  41.         }
  42.         catch (Exception e)
  43.         {
  44.             System.out.println("Invalid 'select' format for url '" + _url + "'.");
  45.         }
  46.         return "";
  47.     }
  48.    
  49.     @Override
  50.     public String toString()
  51.     {
  52.         return result();
  53.     }
  54.    
  55.     public int toInt()
  56.     {
  57.         final String result = result().replaceAll("[^0-9]", "");
  58.         return result.isBlank() ? -1 : Integer.parseInt(result);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement