當我使用HTML Agility Pack抓取H3標籤的InnerText時,我正在拾取額外的字符(Ã,)。
我不確定這些角色來自何處或如何刪除它們。
提取的字符串:
 Week 1
HTML來源:
<h3>
<span> </span>Week 1</h3>
現行代碼:
private void getWeekNumber(string url)
{
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.Load(new System.IO.StringReader(url));
foreach (HtmlAgilityPack.HtmlNode h3 in htmlDoc.DocumentNode.SelectNodes("//h3"))
{
MessageBox.Show(h3.InnerText);
}
}
當前的解決方法 (從stackoverflow上的某個地方被盜,丟失了鏈接):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new System.IO.StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.Load(new System.IO.StringReader(result));
foreach (HtmlAgilityPack.HtmlNode h3 in htmlDoc.DocumentNode.SelectNodes("//h3"))
{
MessageBox.Show(h3.InnerText);
}
你需要先設置編碼...
htmlDoc.Load(new System.IO.StringReader(url), Encoding.UTF8);
這告訴敏捷包該字符是UTF8而不是其他編碼。
你需要在這裡做的原因是,這是在解析它時的重點。在此之後,您將存儲文字Ã,字符。
從互聯網下載HTML後字符串中的字符也可能是有意義的。