【发布时间】:2018-12-03 08:51:37
【问题描述】:
我正在尝试使用 HtmlAgilityPack 从网页 https://www.belastingdienst.nl/rekenhulpen/wisselkoersen/ 获取表格。
到目前为止我的代码是
WebClient webClient = new WebClient();
string page = webClient.DownloadString("https://www.belastingdienst.nl/rekenhulpen/wisselkoersen/");
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
List<List<string>> table = doc.DocumentNode.SelectSingleNode("//table[@class='list_result Result']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("td").Count() > 1)
.Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())
.ToList();
我的问题是网页使用 JavaScript 创建表格,当我尝试读取它时,它会抛出 null 异常,因为网页显示我必须启用 JavaScript。
我也尝试过使用“GET”方法
string Url = "https://www.belastingdienst.nl/rekenhulpen/wisselkoersen/";
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
结果相同。 我已经在 Internet Explorer 中启用了 JavaScript 并更改了注册表
if (Environment.Is64BitOperatingSystem)
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
else //For 32 bit machine
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
如果我使用 WebBrowser 组件,我可以毫无问题地查看网页,但仍然无法列出要列出的表格。
【问题讨论】:
-
你需要无头浏览器。 html由js生成。
-
为什么不使用 WebBrowser 组件并从该组件公开的 DOM 中获取表格?
标签: c# html-table webclient html-agility-pack