C# htmlagility, getting exception when i add header in following code

半世苍凉 提交于 2019-12-24 10:38:05

问题


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/");

回答1:


This works for me in 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);
                }
            }
        }


来源:https://stackoverflow.com/questions/53462643/c-sharp-htmlagility-getting-exception-when-i-add-header-in-following-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!