WebBrowser类并没有帮助我。以下代码无法检索到由我的网络浏览器呈现的HTML代码:
[STAThread]
public static void Main()
{
WebBrowser wb = new WebBrowser();
wb.Navigate("https://www.google.com/#q=where+am+i");
wb.DocumentCompleted += delegate(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)wb.Document.DomDocument;
foreach (IHTMLElement element in doc.all)
{
System.Diagnostics.Debug.WriteLine(element.outerHTML);
}
};
Form f = new Form();
f.Controls.Add(wb);
Application.Run(f);
}
上面只是一个例子。我真正感兴趣的不是找出我所在城镇的解决方法。我只需要了解如何以编程方式检索那种动态生成的数据。
(调用 new System.Net.WebClient.DownloadString("https://www.google.com/#q=where+am+i"),将结果保存在某个地方,查找您当前所在位置的城镇名称,然后告诉我您是否能找到它。)
但是当我从我的Web浏览器(IE或Firefox)访问“https://www.google.com/#q=where+am+i”时,我可以看到我的城镇名称写在网页上。在Firefox中,如果我右键单击城镇名称并选择“检查元素(Q)”,我清楚地看到城镇名称写在HTML代码中,这与WebClient返回的原始HTML非常不同。
在我厌倦了玩System.Net.WebBrowser之后,我决定尝试使用mshtml.HTMLDocument,最终得到了同样无用的原始HTML:
public static void Main()
{
mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)new mshtml.HTMLDocument();
doc.write(new System.Net.WebClient().DownloadString("https://www.google.com/#q=where+am+i"));
foreach (IHTMLElement e in doc.all)
{
System.Diagnostics.Debug.WriteLine(e.outerHTML);
}
}
我想必定有一种优雅的方法可以获取这种信息。目前我所能想到的是在表单中添加一个WebBrowser控件,使其导航到相关的URL,发送"CLRL, A"键,将页面上显示的任何内容复制到剪贴板并尝试解析。然而,这是一个可怕的解决方案。