Advertisement
FancyKing

解析并提取HTML 元素(二)

Apr 3rd, 2020
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. package step3;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import org.jsoup.Jsoup;
  7. import org.jsoup.nodes.Document;
  8. import org.jsoup.nodes.Element;
  9. import org.jsoup.select.Elements;
  10. public class Task {
  11.    
  12.     //通过filePath文件路径获取Docment对象
  13.     public Document getDoc(String filePath) throws IOException{
  14.         /**********   Begin   **********/
  15.  
  16.        
  17.         File file=new File("./backups/hotel.ctrip.com.txt");
  18.         Document doc=Jsoup.parse(file,"UTF-8","http://hotels.ctrip.com/");
  19.         return doc;
  20.         /**********   End   **********/
  21.     }
  22.  
  23.     //获取所有链接
  24.     public List<String> getLinks(Document doc){
  25.         /**********   Begin   **********/
  26.        
  27.  
  28.         List<String> ar=new ArrayList<>();
  29.         Elements kk=doc.select("a[href]");
  30.         for(Element gg:kk){
  31.            ar.add(gg.tagName()+"$"+gg.attr("abs:href")+"("+gg.text()+")");
  32.         }
  33.         return ar;
  34.         /**********   End   **********/
  35.     }
  36.    
  37.     //获取图片
  38.     public List<String> getMedia(Document doc){
  39.         /**********   Begin   **********/
  40.        
  41.  
  42.         List<String> list=new ArrayList<>();
  43.         Elements ll=doc.select("[src]");
  44.         for(Element h:ll){
  45.             if(h.tagName().equals("img")){
  46.                 list.add(h.tagName()+"$"+h.attr("abs:src"));
  47.             }
  48.         }
  49.        
  50.         return list;
  51.         /**********   End   **********/
  52.     }
  53.    
  54.     //获取link[href]链接
  55.     public List<String> getImports(Document doc){
  56.         /**********   Begin   **********/
  57.        
  58.  
  59.         List<String> list=new ArrayList<>();
  60.         Elements kk=doc.select("link[href]");
  61.         for(Element g:kk){
  62.               list.add(g.tagName()+"$"+g.attr("abs:href")+"("+g.attr("rel")+")");
  63.         }
  64.        
  65.         return list;
  66.         /**********   End   **********/
  67.     }
  68.    
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement