【问题标题】:How can i add a webRequest to set timeout when loading a url to document in HtmlAgilityPack?在将 URL 加载到 HtmlAgilityPack 中的文档时,如何添加 webRequest 以设置超时?
【发布时间】:2012-09-17 23:32:29
【问题描述】:

加载网址时我有这段代码:

private List<string> test(string url, int levels,DoWorkEventArgs eve)
        {
            HtmlWeb hw = new HtmlWeb();
            List<string> webSites;
            try
            {
                this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Loading The Url: " + url + "..." , Color.Red); }));
                doc = hw.Load(url);
                this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Done " + Environment.NewLine, Color.Red); }));

有时当它加载 url 时会花费很多时间,因为 url 变量中的网站没有响应。 我想添加一个超时,所以可以说在 X 秒后它会抛出一条消息,比如“有一个超时”。

现在 HtmlAgilityPack 没有任何超时属性或类。 所以我想在我的 Form1 中创建一个新函数,它将使用 webrequest 和 webresponde 并在这个新函数中设置一个超时,然后在加载 url 之前调用这个函数。

有人可以告诉我如何使新功能与我的代码一起使用吗? 还有超时。

谢谢。

【问题讨论】:

    标签: c# html-agility-pack


    【解决方案1】:

    来源:http://blog.jongallant.com/2012/07/htmlagilitypack-set-timeout.html#.VBY-_fmSz3Q

    var web = new HtmlWeb();
    web.PreRequest = delegate(HttpWebRequest webRequest)
    {
         webRequest.Timeout = 4;
         return true;
    };
    var doc = web.Load("http://www.msn.com/");
    

    注意,超时值是请求超时前等待的毫秒数。默认值为 100,000 毫秒(100 秒)

    【讨论】:

    【解决方案2】:

    我对@9​​87654321@ agility 的超时一无所知。但我正在这样使用它。 也许它对你有帮助。 祝你好运。

        String Data = GetURLData(url);
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(Data);
    
    
    
    
        public static string GetURLData(string URL)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
                request.UserAgent = "Omurcek";
                request.Timeout = 4000;
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                return reader.ReadToEnd();
            }   
    
            catch (Exception ex )
            {
                LogYaz("Receive DATA Error : " + URL   + ex.ToString());
                return "";
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2022-10-23
      • 2019-05-15
      • 1970-01-01
      • 2023-01-08
      相关资源
      最近更新 更多