本文介绍了C#htmlagility,在以下代码中添加标头时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时出现异常例外:必须使用适当的属性或方法来修改标题."

I'm getting exception when i run this code Exception "header must be modified using the appropriate property or method."

        HtmlAgilityPack.HtmlWeb web = new HtmlWeb();
        web.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
        web.PreRequest += (request) =>
        {
            request.Headers.Add("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            request.Headers.Add("Accept-Language", "de-DE");
            return true;
        };
        HtmlAgilityPack.HtmlDocument doc = new 
        HtmlAgilityPack.HtmlDocument();

        doc = web.Load("http://www.alfatah.pk/");

推荐答案

这在 https://dotnetfiddle中对我有用. net/AQbs3v :

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.alfatah.pk/");
        request.UserAgent = "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 70.0.3538.77 Safari / 537.36";
 request.Accept= "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        //request.Headers.Add(HttpRequestHeader.AcceptLanguage, "de-DE");

        using (var response = (HttpWebResponse)(request.GetResponse()))
        {
            HttpStatusCode code = response.StatusCode;
            if (code == HttpStatusCode.OK)
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    HtmlDocument htmlDoc = new HtmlDocument();
                    htmlDoc.OptionFixNestedTags = true;
                    htmlDoc.Load(sr);
                    Console.Write(htmlDoc.DocumentNode.InnerText);
                }
            }
        }

这篇关于C#htmlagility,在以下代码中添加标头时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 18:03