我做了一个简单的网络抓取器,为我抓取歌词,然后将其写入数据库。一切正常,但出于某种原因,它用问号替换了一些字符,当我在一个简单的php网页上查看这些信息时,我发现歌词中有很多错误。
I?m = I'm
Let?s = Let's
haven?t = haven't
stuff like that.我知道错误出在c#和我的代码中,因为我在它写入数据库之前放置了一个断点,并将其显示在一个富文本框中。我如何让它正确地显示这些字符?
public static string getSourceCode(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string sourceCode = sr.ReadToEnd();
sr.Close();
resp.Close();
return sourceCode;
}
........
string url = txbURL2.Text;
string sourceCode = sourceCode = WorkerClass.getSourceCode(url);
int startIndex = sourceCode.IndexOf("<td valign=\"top\" width=\"100%\">");
sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
........
//Gets Lyric
startIndex = sourceCode.IndexOf("<br><b>Lyrics:</b><br><br>") + 30;
endIndex = sourceCode.IndexOf(" <br><br>", startIndex);
string lyric = sourceCode.Substring(startIndex, endIndex - startIndex) + "";
rtbLyric.Text = lyric;
//End Lyric发布于 2012-03-28 11:44:59
问题可能出在字符编码上。我的猜测是,你抓取的网页是用UTF8编码的,但在这条线上的某个地方,你正在转换成ASCII码。
有关更多详细信息,请查看名为"What every developer should know about character encoding“的优秀文章。
更新
您可以尝试这样做,尽管StreamReader的默认设置应该是UTF-8:
var encoding = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader(resp.GetResponseStream(), encoding); 发布于 2012-03-28 11:52:01
通过在html代码中搜索字符集来检查编码。
您的代码片段错过了实际的加载过程,因此不可能判断出哪里出了问题。
发布于 2012-07-07 03:05:42
您也可以尝试使用WebClient:
WebClient client = new WebClient { Encoding = Encoding.UTF8 };
string html = client.DownloadString(url);https://stackoverflow.com/questions/9900816
复制相似问题