ฉันจะรับซอร์ส HTML ที่ระบุที่อยู่เว็บใน c # ได้อย่างไร
ฉันจะรับซอร์ส HTML ที่ระบุที่อยู่เว็บใน c # ได้อย่างไร
คำตอบ:
คุณสามารถดาวน์โหลดไฟล์ด้วยคลาส 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);
คำตอบใหม่ล่าสุดล่าสุดและเป็นปัจจุบัน
โพสต์นี้เก่ามาก (เมื่อฉันตอบไป 7 ปี) ดังนั้นคำตอบอื่น ๆ จึงไม่มีคำตอบที่ใช้วิธีใหม่และที่แนะนำซึ่งก็คือHttpClientคลาส
HttpClientถือเป็น API ใหม่และควรแทนที่อันเก่า ( WebClientและWebRequest)
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คลาส (โดยเฉพาะในกรณี async) คุณสามารถอ้างอิงคำถามนี้ได้
หมายเหตุ 1: หากคุณต้องการใช้ async / await
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
}
}
หมายเหตุ 2: หากใช้คุณสมบัติ C # 8
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
คุณสามารถรับได้ด้วย:
var html = new System.Net.WebClient().DownloadString(siteUrl)
DisposeWebClient
วิธี @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");
//...
}