Programming

C #에서 HTML 소스를 다운로드하려면 어떻게해야합니까?

procodes 2020. 8. 15. 14:29
반응형

C #에서 HTML 소스를 다운로드하려면 어떻게해야합니까?


C #에서 웹 주소가 주어진 HTML 소스를 어떻게 얻을 수 있습니까?


WebClient 클래스를 사용하여 파일을 다운로드 할 수 있습니다 .

using System.Net;

using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Or you can get the file content without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}

원래:

using System.Net;
using System.Net.Http;  // in LINQPad, also add a reference to System.Net.Http.dll

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";

string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

Console.WriteLine(source);

다음과 같이 얻을 수 있습니다.

var html = new System.Net.WebClient().DownloadString(siteUrl)

최신, 가장 최근, 최신 답변
이 게시물은 정말 오래되었으므로 (내가 답변했을 때 7 년이되었습니다) 다른 답변 중 어느 누구도 새롭고 권장되는 방식 인 HttpClient수업을 사용하지 않았습니다 .


HttpClient새 API로 간주되며 이전 API ( WebClientWebRequest)를 대체해야합니다.

string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
   using (HttpContent content = response.Content)
   {
      string result = content.ReadAsStringAsync().Result;
   }
}

HttpClient클래스 사용 방법에 대한 자세한 내용은 (특히 비동기 경우) 이 질문을 참조하십시오.


@cms 방법은 MS 웹 사이트에서 제안 된 최신 버전이지만 두 방법 모두 여기에 게시되어 해결하기 어려운 문제가 있었으므로 이제 모든 솔루션을 게시합니다!

문제 : 다음 과 같은 URL을 사용하는 www.somesite.it/?p=1500경우 : 어떤 경우에는 내부 서버 오류 (500)가 발생하지만 웹 브라우저에서는 www.somesite.it/?p=1500완벽하게 작동합니다.

솔루션 : 매개 변수를 이동해야합니다. 작업 코드는 다음과 같습니다.

using System.Net;
//...
using (WebClient client = new WebClient ()) 
{
    client.QueryString.Add("p", "1500"); //add parameters
    string htmlCode = client.DownloadString("www.somesite.it");
    //...
}

여기 공식 문서

참고 URL : https://stackoverflow.com/questions/599275/how-can-i-download-html-source-in-c-sharp

반응형