htmllagilitypack和加载超时

本文关键字:超时 加载 htmllagilitypack | 更新日期: 2023-09-27 17:55:04

我在服务器上的解析器中使用了htmllagilitypack,但我在解析的一个网站上遇到了问题:每天早上6点左右,他们往往会关闭服务器进行维护,这会导致HTMLWeb的Load()方法失效,导致我的应用程序崩溃。你们有更安全的方法将网站加载到htmllagilitypack中吗,或者在c#中进行错误检查以防止我的应用程序崩溃吗?(我的c#有点生疏)。下面是我现在的代码:

HtmlWeb webGet = new HtmlWeb();
HtmlDocument document = webGet.Load(dealsiteLink); //The Load() method here stalls the program because it takes 1 or 2 minutes before it realizes the website is down

谢谢!

htmllagilitypack和加载超时

用try-catch包围调用:

HtmlWeb webGet = new HtmlWeb();
HtmlDocument document;
try
{
    document = webGet.Load(dealsiteLink); 
}
catch (WebException ex)
{
    // Logic to retry (maybe in 10 minutes) goes here
}

确切的重试逻辑将取决于你的应用程序的结构——你可能会发现try-catch块需要放在你的应用程序中更高的位置,需要比这高得多。

我认为WebException是你应该抓住的例外,但我不能确定,因为我找不到文档。您可能会发现还需要捕获TimeoutException

尝试做一个WebRequest。如果你得到一个webeexception,你可以给一些时间再试一次,直到你得到一个响应,一旦你得到一个响应,然后继续使用htmllagilitypack的load方法。

检查

http://msdn.microsoft.com/en-us/library/system.net.webrequest.getresponse.aspx每