public static void main(String[] args) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://www.ln.gov.cn/video/video_57835_1/zydst/2011_99870/d12q/201401/t20140101_1249267.html"); try { client.executeMethod(method); Parser parser = new Parser(method.getResponseBodyAsString()); NodeVisitor visitor = new NodeVisitorExtends(); parser.visitAllNodesWith(visitor); method.releaseConnection(); } catch (IOException e) { e.printStackTrace(); } catch (ParserException e) { e.printStackTrace(); } }
/** * 定义内部类,获取抓取的网页数据中iframe的src包含http://的值。 * 2014-08-14 16:52:10 * @author pengyh * */ private static class NodeVisitorExtends extends NodeVisitor { public void visitTag(Tag tag) { //只获取html中iframe节点的属性 if(tag.getTagName().equalsIgnoreCase("iframe")){ //获取该iframe中的src属性 String srcUrl = tag.getAttribute("src"); //只获取该src中包含有http://的值 if(srcUrl.contains("http://")){ logger.info("获取到iframe中包含http:的地址为[{}]", srcUrl); System.out.println(srcUrl); } } } }
定义的内部类NodeVisitorExtends,可以对抓取到的网页数据进行处理。测试中的为获取iframe中src的属性。
======================以上方法只能获取到flash播放器地址,如果正常的网页播放视频,wap页面使用<iframe src="">便可以正常播放,但是如果wap为嵌入客户端框架,如果该安卓客户端框架集成的播放器为手机自身播放器,有时候需要使用HTML5中<video>标签,此时,就需要获取该flash播放器中真正的视频mp4地址。
此时需要做修改为:
String MP4Url= parseContent("http://video.ln.gov.cn:8080/mas/front/video/main.do?method=exPlay&id=659721&autoPlay=true&logoAlpha=0&logoCss=lb", "utf-8");
http://video.ln.gov.cn:8080/mas/front/video/main.do?method=exPlay&id=659721&autoPlay=true&logoAlpha=0&logoCss=lb为上面抓到的flash播放器地址,将其转成ipad协议或在重新解析。(但是貌似还是会有些视频地址抓不到地址,可能跟视频源有关系。)
MP4Url就为真正视频地址。
/** * 上面的方法只是获取iframe,src flash播放器的地址, 此方法获取flash播放器的视频地址 2014-09-22 16:45:29 * * @author pengyh * @param url * @param charset * @return */ public static String parseContent(String url, String charset) { logger.info("获取flash播放器中的视频地址,url:{}", url); InputStream is = null; HttpClient client = null; Document doc = null; try { client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X)"); GetMethod getMethod = new GetMethod(url); // client.getHostConfiguration().setProxy("192.168.13.19", 7777); client.executeMethod(getMethod); is = getMethod.getResponseBodyAsStream(); doc = Jsoup.parse(is, charset, ""); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } client = null; } logger.info("获取返回结果中source节点的标签"); Elements tag = doc.getElementsByTag("source"); if (tag != null) { String srcVal = tag.attr("src"); logger.info("获取source标签中src的值[{}]。", srcVal); return srcVal; } return null; }
需要引入jar包:httpClient.har、htmlparse.jar、htmllexer.jar
jar包下载地址:http://download.csdn.net/detail/p793049488/7756001