问题
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