我读过的有关此主题的大多数答案都指向 System.Windows.Forms.WebBrowser 类或 Microsoft HTML 对象库程序集中的 COM 接口 mshtml.HTMLDocument。
WebBrowser 类并没有把我带到任何地方。以下代码无法检索我的 Web 浏览器呈现的 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 浏览器(即或 firefox)访问“ https://www.google.com/#q=where+am+i ”时,我看到网页上写着我所在城镇的名称。在 Firefox 中,如果我右键单击城镇名称并选择“Inspect Element (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”,然后将页面上显示的任何内容复制到剪贴板并尝试解析它。不过,这是一个可怕的解决方案。