通过JAVA获取6间房视频,现在很多社会网站都有这个功能,用户输入6间房视频地址后,能找到对应的视频及视频的缩略图,有些社区网站还能获取到视频的时长。
比如:新浪微博就有这个功能,当用户输入视频网址后,就能获取到相应的视频地址及视频的缩略图。
其中要用到一个JAR包,链接地址如下:
http://jsoup.org/packages/jsoup-1.5.2.jar
01.
import
java.io.IOException;
02.
import
java.io.UnsupportedEncodingException;
03.
import
java.net.MalformedURLException;
04.
05.
import
org.jsoup.Jsoup;
06.
import
org.jsoup.nodes.Document;
07.
import
org.jsoup.nodes.Element;
08.
import
org.jsoup.select.Elements;
09.
10.
11.
/**
12.
* 获取6间房视频
13.
* @author sunlightcs
14.
* 2011-3-31
15.
* http://hi.juziku.com/sunlightcs/
16.
*/
17.
public
class
CN6Test {
18.
private
static
String URL =
"http://6.cn/watch/14757577.html"
;
19.
public
static
void
main(String[] args)
throws
Exception{
20.
21.
Document doc = getURLContent();
22.
23.
24.
System.out.println(
"视频标题:"
+doc.title());
25.
26.
/**
27.
* 获取视频缩略图
28.
*/
29.
Element picEt = doc.getElementsByClass(
"summary"
).first();
30.
String pic = picEt.getElementsByTag(
"img"
).first().attr(
"src"
);
31.
System.out.println(
"视频缩略图:"
+pic);
32.
33.
34.
String time = getVideoTime(doc,
"watchUserVideo"
);
35.
36.
if
(time==
null
){
37.
time = getVideoTime(doc,
"watchRelVideo"
);
38.
}
39.
System.out.println(
"视频时长:"
+time);
40.
41.
42.
/**
43.
* 获取视频地址
44.
*/
45.
Element flashEt = doc.getElementById(
"video-share-code"
);
46.
doc = Jsoup.parse(flashEt.attr(
"value"
));
47.
String flash = doc.select(
"embed"
).attr(
"src"
);
48.
49.
System.out.println(
"视频地址:"
+flash);
50.
51.
}
52.
53.
/**
54.
* 获取视频时长
55.
*/
56.
private
static
String getVideoTime(Document doc, String id) {
57.
String time =
null
;
58.
59.
Element timeEt = doc.getElementById(id);
60.
Elements links = timeEt.select(
"dt > a"
);
61.
62.
63.
for
(Element link : links) {
64.
String linkHref = link.attr(
"href"
);
65.
if
(linkHref.equalsIgnoreCase(URL)){
66.
time = link.parent().getElementsByTag(
"em"
).first().text();
67.
break
;
68.
}
69.
}
70.
return
time;
71.
}
72.
73.
/**
74.
* 获取6间房网页的内容
75.
*/
76.
private
static
Document getURLContent()
throws
MalformedURLException, IOException, UnsupportedEncodingException {
77.
Document doc = Jsoup.connect(URL)
78.
.data(
"query"
,
"Java"
)
79.
.userAgent(
"Mozilla"
)
80.
.cookie(
"auth"
,
"token"
)
81.
.timeout(
3000
)
82.
.post();
83.
return
doc;
84.
}
85.
86.
}
http://jsoup.org/packages/jsoup-1.5.2.jar