前言:
网上有很多的抓取网页的代码,大部分是用的都是java api ,HttpClient,HttpURLConnection,io等等
新手看了是不是很晕呀?难道java抓个网页就这么费劲吗?
今天咱们利用apache commons io + 输出流重定向 的方式6行解决网页抓取问题(当然其实可以是5行 呵呵)
准备:
下载apache commons-io 传送门 然后将这个jar加入到你的项目中
- //天气预报网址
- String url="http://www.weather.com.cn/weather/101030100.shtml";
- //是用apache commons io 直接把页面抓成String
- String htmlContent=IOUtils.toString(new URL(url));
- //重定向输出流 到文件
- PrintStream ps=new PrintStream(new File("D:/cxyapi.html"));
- System.setOut(ps);
- System.out.println(htmlContent); //这里的打印不在控制台,而是直接进入文件
- ps.close();