using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Xml.Linq; namespace mxr.mozilla.org_downloader { class Program { static void Main(string[] args) { if (args.Length < 2) { Console.Error.WriteLine("usage mxr.mozilla.org_downloader "); return; } Download(args[0], args[1]); } static void Download(string url, string destDir) { // 创建目录 if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } if (!url.EndsWith("/")) { DownloadFile(url, destDir); } else { DownloadDir(url, destDir + "\" + url.Substring(url.LastIndexOf('/', url.Length - 2) + 1)); } } static void DownloadFile(string url, string destDir) { using (WebClient wc = new WebClient()) { if (url.Contains('?')) { url = url.Substring(0, url.IndexOf('?')); } wc.DownloadFile(url + "?raw=1", destDir + "\" + url.Substring(url.LastIndexOf('/') + 1)); } } static void DownloadDir(string url, string destDir) { // 解析网页 using (WebClient wc = new WebClient()) { string html = Encoding.UTF8.GetString(wc.DownloadData(url)); SgmlDomBuilder sb = new SgmlDomBuilder(); XDocument doc = sb.BuildDocument(html); var maintb = doc.GetElementById("source").NextNode.NextNode as XElement; var trs = from q in maintb.GetElementsByTagName("tr") where q.GetAttributeValue("valign", "none") == "top" select q; foreach (var tr in trs) { var td = tr.FirstNode.NextNode as XElement; var a = td.Elements().First(); if (a.GetInnerHtml() != "Parent directory") { string href = a.GetAttributeValue("href", null); if (href != null) { Download("http://mxr.mozilla.org" + href, destDir); } } } } } } }源代码:mxr.mozilla.org downloader_src 程序:mxr.mozilla.org downloader
mxr.mozilla.org是mozilla的代码查看网站,上面有丰富的代码资源,但是上边没有打包下载的功能,只能单个单个文件的下载,用起来会非常的麻烦。 今天没啥事,想研究一下firefox的编码识别模块,需要到mxr.mozilla.org上去下载代码。去网上找了一圈也没有找到批量下载的方法或工具。 本想一个一个文件下载,但是发现文件数量还是比较大的,很麻烦,所以决定写个工具来下载。 工具用C#写成,用到了SqmlReader来解析html代码。 用法也很简单,usage mxr.mozilla.org_downloader <url> <donwload path> 代码如下,写得比较戳,没有太多的考虑效率问题: