【问题标题】:Problem pulling data from website in .NET and C#从 .NET 和 C# 中的网站提取数据的问题
【发布时间】:2010-06-14 20:13:24
【问题描述】:

我编写了一个网页抓取程序来访问页面列表并将所有 html 写入文件。问题是,当我拉出一段文本时,一些字符会写成“�”。如何将这些字符拉到我的文本文件中?这是我的代码:

string baseUri = String.Format("http://www.rogersmushrooms.com/gallery/loadimage.asp?did={0}&blockName={1}", id.ToString(), name.Trim());

// our third request is for the actual webpage after the login.
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(baseUri);
request.Method = "GET";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)";
//get the response object, so that we may get the session cookie.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());

// and read the response
string page = reader.ReadToEnd();

StreamWriter SW;
string filename = string.Format("{0}.txt", id.ToString());
SW = File.AppendText("C:\\Share\\" + filename);

SW.Write(page);

reader.Close();
response.Close();

【问题讨论】:

标签: c# asp.net httpwebresponse streamreader web-scraping


【解决方案1】:

您正在将一个名为 loadimage 的页面保存到一个文本文件中。你确定这真的都是文字吗?

无论哪种方式,您都可以使用System.Net.WebClient.DownloadFile()为自己节省大量代码。

【讨论】:

    【解决方案2】:

    您需要在此行中指定您的编码:

    StreamReader reader = new StreamReader(response.GetResponseStream());
    

    File.AppendText("C:\\Share\\" + filename); 使用 UTF-8

    【讨论】:

      【解决方案3】:

      指定 Unicode 编码,如下所示:

      New StreamReader(response.GetResponseStream(), Text.Encoding.UTF8)
      

      ..StreamWriter 也一样

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        • 2020-09-17
        • 1970-01-01
        • 2020-10-20
        • 2018-04-03
        • 2022-06-16
        • 2015-08-26
        相关资源
        最近更新 更多