如何通过C#获取HTML页面源代码

Red*_*rmy 4 c#

我想保存在本地驱动器上完整的网页ASP .htmURL链接,但我没有成功。

public StreamReader Fn_DownloadWebPageComplete(string link_Pagesource)
{
     //--------- Download Complete ------------------
     //  using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
     //   {

     //client
     //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(link_Pagesource);

                    //webRequest.AllowAutoRedirect = true;
                    //var client1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link_Pagesource);
                    //client1.CookieContainer = new System.Net.CookieContainer();


                 //   client.DownloadFile(link_Pagesource, @"D:\S1.htm");

              //  }
         //--------- Download Page Source ------------------
 HttpWebRequest URL_pageSource = (HttpWebRequest)WebRequest.Create("https://www.digikala.com");

                    URL_pageSource.Timeout = 360000;
                    //URL_pageSource.Timeout = 1000000;
                    URL_pageSource.ReadWriteTimeout = 360000;
                   // URL_pageSource.ReadWriteTimeout = 1000000;
                    URL_pageSource.AllowAutoRedirect = true;
                    URL_pageSource.MaximumAutomaticRedirections = 300;

                    using (WebResponse MyResponse_PageSource = URL_pageSource.GetResponse())
                    {

                        str_PageSource = new StreamReader(MyResponse_PageSource.GetResponseStream(), System.Text.Encoding.UTF8);
                        pagesource1 = str_PageSource.ReadToEnd();
                        success = true;
                    }
Run Code Online (Sandbox Code Playgroud)

错误:

尝试了太多的自动重定向。

通过此代码尝试尝试,但未成功。

许多网址使用此代码成功,但是此网址未成功。

Hak*_*tık 5

这是方法

    string url = "https://www.digikala.com/";

    using (HttpClient client = new HttpClient())
    {
        using (HttpResponseMessage response = client.GetAsync(url).Result)
        {
            using (HttpContent content = response.Content)
            {
                string result = content.ReadAsStringAsync().Result;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

并且result变量将包含该页面,因为HTML您可以将其保存到这样的文件中

System.IO.File.WriteAllText("path/filename.html", result);
Run Code Online (Sandbox Code Playgroud)

注意您必须使用名称空间

using System.Net.Http;
Run Code Online (Sandbox Code Playgroud)

更新,如果你使用的是旧版VS然后就可以看到这个答案,使用WebClientWebRequest为了同样的目的,但实际上更新VS是一个更好的解决方案。

  • 虽然使用“.Result”确实有效,但它将异步调用转换为阻塞同步调用。最好“等待”异步方法调用(然后不需要使用 .Result)以从异步特性中受益。 (2认同)