目录
在网上看到一本书,Data Structures and Algorithms来回翻网页比较麻烦,就用C#做了一个自动下载到本地的小程序
1 核心代码:
1.1 获取html页面到本地
public void getHtmlPage(string url, string outPath)
{
try {
WebClient MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
string pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句
//string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
Console.WriteLine(pageHtml);//在控制台输入获取的内容
using (StreamWriter sw = new StreamWriter(outPath))//将获取的内容写入文本
{
sw.Write(pageHtml);
}
//MessageBox.Show("success");
}
catch(WebException webEx) {
Console.WriteLine(webEx.Message.ToString());
}
}
1.2 批量处理按钮
private void btnHtmlToPdf_Click(object sender, EventArgs e)
{
int startHtml = int.Parse(txt_startPage.Text);
int endHtml = int.Parse(txt_endPage.Text);
// HtmlToPdf(@"http://lcm.csa.iisc.ernet.in/dsa/node4.html");
string srcPath = txt_srcPath.Text;
string dstPath = txt_outHtmlDir.Text;
string pageFlag = txt_indexFlag.Text;
string tmpPage = String.Empty;
string dstFilePath = string.Empty;
progressBar1.Minimum = 0;
progressBar1.Maximum = endHtml - startHtml;
for (int i = startHtml; i < endHtml; i++)
{
tmpPage = srcPath + pageFlag + i.ToString() + ".html";
dstFilePath = dstPath + "\\" + i.ToString() + ".html";
getHtmlPage(tmpPage, dstFilePath);
progressBar1.Value++;
}
}
2 程序界面:
测试:
下载结果:
注:
- dstFilePath = dstPath + "\\" + i.ToString() + ".html";修改为dstFilePath = dstPath + "\\"+ pageFlag+ i.ToString() + ".html";可以保留网页的原始索引
- 手动下载dsa.html文件,可以实现html之间的自由切换
- 我的处理方式是:用以上源码生成html后,在使用拖把更名器进行了处理
- 后续可以尝试将这些html文件转化为pdf文件更方便查看