开发者体验:Java抓取百度Top500歌曲及源码

开发 后端
本文主要介绍一位开发者用Java抓取百度Top500歌曲及源码下载的方法。这种方法是为了批量播放歌曲以及做集中的展示之用。

主要的工作就是如何通过Java抓取***的Baidu好听的歌曲,Java抓取的工作主要包括3个属性:歌名、歌曲在线播放地址和歌词内容(符合LRC歌词格式),目前完成歌曲和歌曲地址抓取,由于百度的歌曲地址很多通过js获取,所以歌曲地址获取我这里使用搜狗音乐搜索方便些,所有的源码如下:

  1. /** *//**   
  2.   http://www.bt285.cn http://www.5a520.cn   
  3.   */   
  4.   package com.common.utils;   
  5.   import Java.io.BufferedReader;   
  6.   import java.io.ByteArrayOutputStream;   
  7.   import java.io.IOException;   
  8.   import java.io.InputStream;   
  9.   import java.io.InputStreamReader;   
  10.   import java.io.OutputStreamWriter;   
  11.   import java.io.UnsupportedEncodingException;   
  12.   import java.net.HttpURLConnection;   
  13.   import java.net.MalformedURLException;   
  14.   import java.net.URL;   
  15.   import java.net.URLConnection;   
  16.   import java.net.URLDecoder;   
  17.   import java.net.URLEncoder;   
  18.   import java.util.ArrayList;   
  19.   import java.util.HashSet;   
  20.   import java.util.List;   
  21.   import java.util.Set;   
  22.   import java.util.TreeSet;   
  23.   import java.util.regex.Matcher;   
  24.   import java.util.regex.Pattern;   
  25.   import org.htmlparser.Node;   
  26.   import org.htmlparser.NodeFilter;   
  27.   import org.htmlparser.Parser;   
  28.   import org.htmlparser.filters.NodeClassFilter;   
  29.   import org.htmlparser.filters.OrFilter;   
  30.   import org.htmlparser.nodes.TextNode;   
  31.   import org.htmlparser.tags.LinkTag;   
  32.   import org.htmlparser.util.NodeList;   
  33.   import org.htmlparser.util.ParserException;   
  34.   import com.common.doc.FileOperUtils;   
  35.   class Song{   
  36.   private String name;   
  37.   private String url;   
  38.   private String lrc;   
  39.   public Song(String name,String url){   
  40.   this.name = name;   
  41.   this.url = url;   
  42.   this.lrc = "";   
  43.   }   
  44.   public String getName() {   
  45.   return name;   
  46.   }   
  47.   public void setName(String name) {   
  48.   this.name = name;   
  49.   }   
  50.   public String getUrl() {   
  51.   return url;   
  52.   }   
  53.   public void setUrl(String url) {   
  54.   this.url = url;   
  55.   }   
  56.   public String getLrc() {   
  57.   return lrc;   
  58.   }   
  59.   public void setLrc(String lrc) {   
  60.   this.lrc = lrc;   
  61.   }   
  62.   }   
  63.   public class BaiduMP3 {   
  64.   public static String visitURL(String strUrl) {   
  65.   URL url = null;   
  66.   try {   
  67.   url = new URL(strUrl);   
  68.   } catch (MalformedURLException e) {   
  69.   e.printStackTrace();   
  70.   }   
  71.   URLConnection conn = null;   
  72.   try {   
  73.   conn = url.openConnection();   
  74.   conn.setDoOutput(true);   
  75.   } catch (IOException e) {   
  76.   System.out.println("e:"+e.getMessage());   
  77.   }   
  78.   OutputStreamWriter out;   
  79.   try {   
  80.   out = new OutputStreamWriter(conn.getOutputStream(), "GBK");   
  81.   out.flush();   
  82.   out.close();   
  83.   } catch (UnsupportedEncodingException e2) {   
  84.   e2.printStackTrace();   
  85.   } catch (IOException e2) {   
  86.   e2.printStackTrace();   
  87.   }   
  88.   // 接收返回信息   
  89.   BufferedReader rd = null;   
  90.   try {   
  91.   rd = new BufferedReader(   
  92.   new InputStreamReader(conn.getInputStream()));   
  93.   return rd.readLine();   
  94.   } catch (IOException e1) {   
  95.   e1.printStackTrace();   
  96.   }   
  97.   return "";   
  98.   }   
  99.   /** *//**   
  100.   * 功能说明:访问指定的URL并检查返回结果。   
  101.   * @param strUrl   
  102.   * @param successFlag 请求成功的标识,比如包含“_SUCCESS”字。   
  103.   * @return   
  104.   */   
  105.   public static String visitURL(String strUrl, String successFlag) {   
  106.   boolean rs = false;   
  107.   HttpURLConnection jconn = null;   
  108.   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();   
  109.   try {   
  110.   URL url = new URL(strUrl);   
  111.   jconn = (HttpURLConnection) url.openConnection();   
  112.   jconn.setDoOutput(true);   
  113.   jconn.setDoInput(true);   
  114.   jconn.connect();   
  115.   InputStream in = jconn.getInputStream();   
  116.   byte[] buf = new byte[4096];   
  117.   int bytesRead;   
  118.   while ((bytesRead = in.read(buf)) != -1) {   
  119.   byteArrayOutputStream.write(buf, 0, bytesRead);   
  120.   }   
  121.   String strRead = new String(byteArrayOutputStream.toByteArray(),"GBK");   
  122.   return strRead;   
  123.   } catch (MalformedURLException e) {   
  124.   e.printStackTrace();   
  125.   } catch (IOException e) {   
  126.   e.printStackTrace();   
  127.   } finally {   
  128.   jconn.disconnect();   
  129.   try {   
  130.   byteArrayOutputStream.close();   
  131.   } catch (IOException e) {   
  132.   e.printStackTrace();   
  133.   }   
  134.   }   
  135.   return "";   
  136.   }   
  137.   private static boolean isTrimEmptyOrBlank(String astr) {   
  138.   if ((null == astr) || (astr.length() == 0) || " ".equals(astr)) {   
  139.   return true;   
  140.   }   
  141.   astrastr = astr.trim();   
  142.   if ((null == astr) || (astr.length() == 0)) {   
  143.   return true;   
  144.   }   
  145.   return false;   
  146.   }   
  147.   private static String getFilteredContent(String htmlContent, String reg,int i) {   
  148.   String content = "";   
  149.   int k=1;   
  150.   Pattern pp = Pattern.compile(reg, Pattern.DOTALL);   
  151.   Matcher m = pp.matcher(htmlContent);   
  152.   while (m.find()) {   
  153.   content = m.group();   
  154.   if(k++==i)   
  155.   break;   
  156.   }   
  157.   return content;   
  158.   }   
  159.   public static List getBaiduSongs(){   
  160.   List ss = new ArrayList();   
  161.   String htmlContent = visitURL("http://list.mp3.baidu.com/topso/mp3topsong.html?id=1?top2","s");   
  162.   String encode = "GBK";   
  163.   //      System.out.println("===========================================================================");   
  164.   //      System.out.println(htmlContent);   
  165.   //      System.out.println("===========================================================================");   
  166.   String reg = "(.*?)";   
  167.   htmlContent = getFilteredContent(htmlContent,reg,0);   
  168.   //FileOperUtils.writeFile("c:\\1.html", htmlContent, false);   
  169.   String line = "",lineurl="";   
  170.   Node anode = null;   
  171.   TextNode textnode = null;   
  172.   try {   
  173.   Parser parser = Parser.createParser(htmlContent, encode);   
  174.   NodeClassFilter textFilter = new NodeClassFilter(LinkTag.class);   
  175.   OrFilter lastFilter = new OrFilter();   
  176.   lastFilter.setPredicates(new NodeFilter[] { textFilter });   
  177.   NodeList nodeList = parser.parse(lastFilter);   
  178.   Node[] nodes = nodeList.toNodeArray();   
  179.   for (int i = 0; i < nodes.length; i++) {   
  180.   anode = (Node) nodes[i];   
  181.   if(anode instanceof LinkTag){   
  182.   LinkTag txt = (LinkTag)anode;   
  183.   line = txt.getLinkText();   
  184.   if(txt.getPreviousSibling()!=null){   
  185.   if(txt.getPreviousSibling().toString().indexOf("(")>=0)   
  186.   continue;   
  187.   }   
  188.   line = txt.getLinkText();   
  189.   lineurl = txt.getAttribute("href");   
  190.   //System.out.println(txt.getLink());   
  191.   }   
  192.   if (isTrimEmptyOrBlank(line)||isTrimEmptyOrBlank(lineurl))   
  193.   continue;   
  194.   ss.add(new Song(line,getSongURL(line)));   
  195.   }   
  196.   } catch (ParserException pe) {   
  197.   pe.printStackTrace();   
  198.   }   
  199.   return ss;   
  200.   }   
  201.   private static String getSongURL(String songname){   
  202.   try {   
  203.   String ss = URLEncoder.encode(songname,"GBK");   
  204.   String htmlContent = visitURL("http://so.mp3.qihoo.com/?type=0&ssrc=s&kw="+ss,"s");   
  205.   String encode = "GBK";   
  206.   http://www.feng123.com   
  207.   String reg = "(.*?)";  http://www.5a520.cn   
  208.   htmlContent = getFilteredContent(htmlContent,reg,1);   
  209.   String line = "",lineurl="";   
  210.   Node anode = null;   
  211.   TextNode textnode = null;   
  212.   Parser parser = Parser.createParser(htmlContent, encode);   
  213.   NodeClassFilter textFilter = new NodeClassFilter(LinkTag.class);   
  214.   OrFilter lastFilter = new OrFilter();   
  215.   lastFilter.setPredicates(new NodeFilter[] { textFilter });   
  216.   NodeList nodeList = parser.parse(lastFilter);   
  217.   Node[] nodes = nodeList.toNodeArray();   
  218.   for (int i = 0; i < nodes.length; i++) {   
  219.   anode = (Node) nodes[i];   
  220.   if(anode instanceof LinkTag){   
  221.   LinkTag txt = (LinkTag)anode;   
  222.   line = txt.getLinkText();   
  223.   lineurl = txt.getAttribute("href");   
  224.   if(!isTrimEmptyOrBlank(lineurl) && lineurl.startsWith("down.html")){   
  225.   String s = getFilteredContent(lineurl,"u=(.*?)\\&",0);   
  226.   if(!s.equals("")&&s.length()>5){   
  227.   s = Utils.replace(s, "u=", "");   
  228.   s = Utils.replace(s, "&", "");   
  229.   s = URLDecoder.decode(s,"GBK");   
  230.   return s;   
  231.   }   
  232.   }   
  233.   }   
  234.   }   
  235.   } catch (Exception pe) {   
  236.   pe.printStackTrace();   
  237.   }   
  238.   return "";   
  239.   }   
  240.   public static void main(String[] args) throws Exception{   
  241.   List ss = getBaiduSongs();   
  242.   int idx = 0;   
  243.   for(Song s:ss){   
  244.   System.out.println((++idx)+":"+s.getName()+"->"+s.getUrl());   
  245.   }   
  246.   //      String ss = getSongURL("国家");   
  247.   //      System.out.println(ss);   
  248.   //      String s = URLDecoder.decode("http%3A%2F%2F http://www.5a520.cn %2F%B9%FA%BC%D2.mp3","GBK");   
  249.   //      System.out.println(s);   
  250.   }   
  251.   } 

至此Java抓取百度Top500歌曲及源码的工作完成。

【编辑推荐】

  1. Java连接MySQL中文乱码处理
  2. 在Java应用程序中使用Jfreechart配置
  3. Java虚拟机内部构成浅析
  4. 浅谈Java线程的生命周期
  5. 关于Java继承的一些复习
责任编辑:彭凡 来源: IT专家网论坛
相关推荐

2021-01-28 06:07:32

百度搜索搜索引擎 应用

2012-03-23 11:20:08

百度开发者中心

2012-03-23 08:34:44

百度开发者大会

2012-03-26 16:00:17

FLASH开发

2012-04-25 10:19:48

2012百度开发者

2011-09-06 16:33:35

百度世界2011

2012-10-28 10:56:18

2013-08-30 16:39:07

百度侯震宇移动

2013-08-30 11:05:52

百度百度云

2011-05-12 10:05:28

百度Web APP应用

2019-08-09 17:00:18

2013-04-12 16:15:21

百度移动

2012-10-29 11:17:41

百度移动统计

2013-09-02 11:33:38

百度

2011-05-10 08:26:26

百度Web App应用

2012-01-11 13:10:47

百度沙龙

2011-12-08 14:29:20

开发者说

2011-05-13 13:34:08

百度Web APP应用

2012-10-29 11:16:21

百度SDK3.0

2011-12-08 14:01:32

开发者说
点赞
收藏

51CTO技术栈公众号