HtmlAgilityPack.dll을 사용하여 페이지를 스크랩하려고 시도했지만 일부 URL이 함수에 들어가서 오류가 발생하여 try-catch 블록에서 catch 할 수 없습니다. 그래서 누구든지 나를 도울 수 있습니까?
오류 : HtmlAgilityPack.dll에서 'System.StackOverflowException'형식의 처리되지 않은 예외가 발생했습니다.
public void HtmlLoad(string url)
{
try
{
HttpWebRequest myHttpWebRequest = null; //Declare an HTTP-specific implementation of the WebRequest class.
HttpWebResponse myHttpWebResponse = null; //Declare an HTTP-specific implementation of the WebResponse class
//Create Request //
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/html; encoding='utf-8'";
//Get Response
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
Stream data = myHttpWebResponse.GetResponseStream();//client.OpenRead(url);
doc.Load(data);
data.Close();
}
catch (Exception ex) { throw ex; }
}
이걸 깨끗하게해볼 수 있어요.
public static async Task<int> HtmlLoadAsync(string url/*, bool addUserAgent = false*/)
{
try
{
var client = new HttpClient();
//if (addUserAgent) OPTIONAL
//{
// client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
//}
//client.Timeout = TimeOut;
var response = client.GetStringAsync(url);
var urlContents = await response;
var document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(urlContents);
// process document now
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return 0;
}
이제 부르세요.
private async void Process()
{
await HtmlLoadAsync("http://....");
}