Skip to main content
 首页 » 编程设计

c#之无法从网页下载源

2024年02月23日18Renyi-Fan

我正在尝试使用 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"); 

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

请您参考如下方法:

使用 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"); 

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