BBC Learning English在线3大系列课程:Lower intermediate、Intermediate、English My Way?声音很悦耳,尤其是Jamaica Inn和The Importance of Being Earnest,堪称完美,百听不厌,这对于英语兴趣的培养和英语能力的提升非常有帮助。到目前为止,这些课程的mp3和pdf文件已经有518个,而且还在持续增长中,如果能写个程序自动地把这些文件下载下来就好了,要是手工一个个下载,那得累死吧,尤其是对那些还从来没有学过这个课程的人。
下载下来后将文件拷贝到手机上,在挤地铁挤公交的时候戴着耳机听一听,充分利用时间嘛,听不懂的还可以看看录音稿,要不然直接在BBC的网站上看,那太不方便了。
首先,我们使用maven引入jsoup依赖:
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.7.2</version> </dependency>
?
接下来就可以写代码了:
import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Created by ysc on 10/21/15. * 下载BBC Learning English在线课程 */ public class BBC { public static void main(String[] args) { String path = "/Users/apple/百度云同步盘/BBC/"; download("lower-intermediate", 30, path); download("intermediate", 25, path); download("emw", 15, path); } /** * BBC Learning English在线课程类型: * 1、lower-intermediate http://www.bbc.co.uk/learningenglish/english/course/lower-intermediate * 2、intermediate http://www.bbc.co.uk/learningenglish/english/course/intermediate * 3、emw http://www.bbc.co.uk/learningenglish/english/course/emw * @param type 课程类型 * @param count 课数 * @param path 保存到本地的路径 */ public static void download(String type, int count, String path) { int timeout = 300000; for(int i=1; i<=count; i++) { try { String url = "http://www.bbc.co.uk/learningenglish/english/course/" + type + "/unit-" + i + "/downloads"; System.out.println("connect " + url); Document doc = Jsoup.connect(url).timeout(timeout).get(); Elements elements = doc.select("a"); for (Element element : elements) { try { String href = element.attr("href"); //只下载mp3、mp4和pdf文件 if (href.endsWith(".mp3") || href.endsWith(".mp4") || href.endsWith(".pdf")) { //提取文件名称 String[] attr = href.split("/"); String fileName = attr[attr.length - 1]; System.out.println("unit " + i + "、find resource: " + href); //确保本地路径存储 Path dir = Paths.get(path, type); if(!Files.exists(dir)){ //不存在则新建 dir.toFile().mkdirs(); } //保存文件的完整本地路径 Path out = Paths.get(path, type, fileName); //如果文件存在则表示之前已经下载过,本次不用下载 //因为BBC的访问不稳定,所以可能需要执行程序多次才能完整下载完毕,所以这里要处理已存在文件的问题 if (!Files.exists(out)) { //下载文件 Connection.Response response = Jsoup.connect(href).maxBodySize(0).ignoreContentType(true).timeout(timeout).execute(); //将文件保存到本地 Files.write(out, response.bodyAsBytes()); System.out.println("unit " + i + "、save resource to: " + out); } else { System.out.println("unit " + i + "、resource exist, don‘t need to download"); } } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } } }
?
代码也可以从我的开源项目HtmlExtractor中获取。
对于不会写程序只想学英语的同学可以从我的百度网盘直接下载。
?
?
?
?
?
如何写程序自动下载BBC Learning English的所有在线课程
原文:http://yangshangchuan.iteye.com/blog/2250880