下载 HTML 页面并将其编码为文件
Download and encode HTML page into file
我喜欢下载一些使用charset="UTF-8"
的网页
此页面是示例:http://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_2003
我总是以这样的特殊字符结尾:
Beyoncé 而不是 Beyoncé
我尝试了以下代码:
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.DownloadFile(url, fileName);
或这个:
WebClient client = new WebClient();
Byte[] pageData = client.DownloadData(url);
string pageHtml = Encoding.UTF8.GetString(pageData);
System.IO.File.WriteAllText(fileName, pageHtml);
我做错了什么?
我只想要一种简单的方法来下载网页并将它们写入文件。完成后,我将从这些文件中提取数据,显然我想要 "normal" 个字符,就像我在原始网页上看到的那样,而不是一些特殊字符。
问题是 WriteAllText 方法没有在文件中写入 UTF-8 编码的文本。
您应该添加编码:
System.IO.File.WriteAllText(fileName, pageHtml, Encoding.UTF8);
我喜欢下载一些使用charset="UTF-8"
的网页
此页面是示例:http://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_2003
我总是以这样的特殊字符结尾:
Beyoncé 而不是 Beyoncé
我尝试了以下代码:
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.DownloadFile(url, fileName);
或这个:
WebClient client = new WebClient();
Byte[] pageData = client.DownloadData(url);
string pageHtml = Encoding.UTF8.GetString(pageData);
System.IO.File.WriteAllText(fileName, pageHtml);
我做错了什么?
我只想要一种简单的方法来下载网页并将它们写入文件。完成后,我将从这些文件中提取数据,显然我想要 "normal" 个字符,就像我在原始网页上看到的那样,而不是一些特殊字符。
问题是 WriteAllText 方法没有在文件中写入 UTF-8 编码的文本。 您应该添加编码:
System.IO.File.WriteAllText(fileName, pageHtml, Encoding.UTF8);