[C#] ดึงข้อมูลจากเวบไซต์ที่เป็นภาษาไทยด้วย C# พร้อมตัด HTML tag

เนื่องด้วยโปรเจคจบของออฟมีส่วนที่ต้องทำการดึงข้อมูลจากเวบไซต์ที่เป็นภาษาไทย และต้องการนำข้อมูลส่วนที่ไม่ใ่ช่ HTML tag ต่างๆออกไปด้วย แบบว่าอยากได้แต่ข้อมูลเพรียวๆเลยนั่นแหละคะ พอทำได้แล้วก็เลยเอามาอัพบล็อคซะเลยเผื่อใครเจอปัญหาหรืออยากทำเหมือนกัน
-
ขั้นตอนหลักๆของการทำงาน
- ทำการดึงข้อมูลจาก URL ที่ระบุ
- ตัด Tag ต่างๆ ออกให้เหลือแต่ข้อมูล
- ทำการเซฟข้อมูลที่ได้ลงไฟล์
-
ทำการดึงข้อมูลจาก URL ที่ระบุ
public void GetContentFromWeb()
{
WebClient objWebClient = new WebClient();
String strURL = "http://don-jai.com/movie-the-ugly-truth/";
String strRequest;
UTF8Encoding objUTF8 = new UTF8Encoding();
Byte[] byteRequest = objWebClient.DownloadData(strURL);
string fileName = "web.txt";
strRequest = objUTF8.GetString(byteRequest);
string content = GetContent(strRequest);
Byte[] f = System.Text.Encoding.UTF8.GetBytes(content);
SaveFile(f, fileName);
}
-
ตัด Tag ต่างๆ ออกให้เหลือแต่ข้อมูล
public static string GetContent(string strRequest)
{
// Remove HTML Tag
Regex regex = new Regex(@"\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline);
MatchCollection matches = regex.Matches(strRequest);
foreach (Match match in matches)
{
int begin = strRequest.IndexOf(match.Value);
strRequest = strRequest.Remove(begin, match.Value.Length);
}
return strRequest;
}
-
ทำการเซฟข้อมูลที่ได้ลงไฟล์
public string SaveFile(byte[] f, string fileName)
{
try
{
MemoryStream ms = new MemoryStream(f);
FileStream fs = new FileStream
(System.Web.Hosting.HostingEnvironment.MapPath("~/Compare2File/") +
fileName, FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
return "OK";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
Leave a comment