java歌词解析代码_Java Jsoup从Html中解析歌词

import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

import org.jsoup.nodes.Element;

import org.jsoup.select.Elements;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

public class Test

{

private static String songName = "北京北京";

public static void main(String args[])

{

Test getLrc = new Test();

String lrcUrl = getLrc.getLrcUrl(songName);

System.out.println(lrcUrl);

String lrcTxt = getLrc.getLrcText(lrcUrl);

System.out.println(lrcTxt);

}

public String getLrcUrl(String song)

{

String lrcUrl = null;

try

{

String songEnc = toBrowserCode(song, "UTF-8");

System.out.println(songEnc);

Document doc = Jsoup.connect(

"http://www.9ilrc.com/search.php?keyword=" + songEnc

+ "&radio=song").get();

Elements links = doc.select("a[href]");

for (Element link : links)

{

if (toBrowserCode(trim(link.text(), 15), "UTF-8").equals(

songEnc))

{

lrcUrl = link.attr("abs:href");

break;

}

}

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

return lrcUrl;

}

public String getLrcText(String url)

{

String lrcTxt = null;

try

{

Document doc = Jsoup.connect(url).get();

Elements links = doc.select("[id]");

for (Element ele : links)

{

if (ele.attr("id").equals("txt"))

{

lrcTxt = ele.text().replace(" ", "\n");

break;

}

}

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

return lrcTxt;

}

private static String trim(String s, int width)

{

if (s.length() > width)

return s.substring(0, width - 1) + ".";

else

return s;

}

public String toBrowserCode(String word, String encoding)

throws UnsupportedEncodingException

{

byte[] textByte = word.getBytes(encoding);

StringBuilder strBuilder = new StringBuilder();

for (int j = 0; j < textByte.length; j++)

{

String hexStr = Integer.toHexString(textByte[j] & 0xff);

strBuilder.append("%" + hexStr.toUpperCase());

}

return strBuilder.toString();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值