为什么我要拾取外国字符,如何删除它们?

时间:2012-07-19 14:22:53

标签: c# html string html-agility-pack

当我使用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);
}

2 个答案:

答案 0 :(得分:4)

您需要先设置编码...

htmlDoc.Load(new System.IO.StringReader(url), Encoding.UTF8);

这告诉敏捷包该字符是UTF8而不是其他编码。

你需要在这里做的原因是,这是在解析它时的重点。在此之后,您将存储文字字符。

Characters in string changed after downloading HTML from the internet也可能是有意义的。

答案 1 :(得分:1)

可能是您的字符编码,将编码设置为UTF-8