【问题标题】:Trouble download source from a web page无法从网页下载源
【发布时间】:2011-09-15 16:20:59
【问题描述】:

我正在尝试使用 c# 为学校项目下载此网页的源代码。
这是我试图获取的页面:
http://www.epicurious.com/tools/fooddictionary/entry?id=1650

我试过这样的代码

 HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");

并通过使用

 WebClient client = new WebClient();
string value = client.DownloadString("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");

这两种方法都没有让我获得页面源。任何帮助将不胜感激。

【问题讨论】:

  • 当你说“来源”时,你的意思是 HTML,对吧?

标签: c# download webclient httprequest webpage


【解决方案1】:

使用 HttpWebRequest.Create

try
{
    WebRequest req = HttpWebRequest.Create("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
    req.Method = "GET";

    string source;
    using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
    {
        source = reader.ReadToEnd();
    }
}
catch (Exception ex)
{
    //Log the exception 
    MessageBox.Show(ex.ToString());
}

使用下载字符串

WebClient client = new WebClient();
string reply = client.DownloadString("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");

以上方法对我来说效果很好。如果有异常,请检查..

【讨论】:

  • 我会赞成您的示例使用 ex.Message 的这个例外。应该是ex.ToString()
  • 通常我们不会向用户显示完整的异常,而是记录完整的异常。这就是我使用 exception.Message 的原因。在这种情况下,我们可以显示完整的异常来查找问题。谢谢.. 更新了我的答案
  • 赞成。我的感觉是,如果您要展示异常处理,那么请向新手展示如何使用ex.ToString()。否则,那么认为ex.Message 信息就足够了。
【解决方案2】:

这个怎么样...

string sourceCode = "";
Uri site = new Uri("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
WebRequest request = WebRequest.Create(site);
using(StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.ASCII)){
    sourceCode = reader.ReadToEnd();
}

“使用”语句将为您关闭流。注意:在流上调用 close 也会在它正在使用的任何流上调用 class,这就是为什么你只需要单个 using 语句

【讨论】:

  • -1:也许您可以编辑您的答案以显示正确使用using?然后我会删除反对票。
  • @John Saunders,怎么样?
  • 足够好了。你真的应该打破 GetResponse 和 GetResponseStream 调用,但这会做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
相关资源
最近更新 更多