我想以编程方式(WPF,C#)登录我的财务帐户网站(https)并检索我的部分帐户数据。由于该站点使用cookie和其他会话验证,我认为最好的方法是使用Web浏览器控件,而不是httpWebRequest。我似乎无法捕捉屏幕内容。
我能够使用winforms成功完成此操作,但我想在WPF中完成此操作。以下是winforms项目的代码片段:
webBrowser1.Navigate( @"https://myfinancialaccountURL" );
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(
wb1DocumentCompleted );
private void wb1DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e )
{
string wb1LogonScreen = webBrowser1.DocumentText;
--- process the data, etc. ---
}
以下是WPF尝试的代码段:
webBrowser1.Navigated += new NavigatedEventHandler( webBrowser1_Navigated );
webBrowser1.Navigate( @"https:myfinancialaccountURL" );
我已经广泛研究了WPF Web浏览器控件,它有一个Document属性,但我无法弄清楚如何获取内容(或内部文本)。
我研究了这个,但仍然无法找到答案。请告诉我是否需要提供更多信息。我非常感谢你的帮助。
感谢名单
答案 0 :(得分:1)
您可以将Document属性作为MSHTML.Document读取,然后使用它来获取文本。您需要在项目中包含Microsoft.mshtml库。
mshtml.HTMLDocument doc = null;
string docState = string.Empty;
// CODE TO ENSURE THAT THE DOCUMENT AND THE SCRIPTS HAVE LOADED
Action getDocState = () =>
{
doc = wb.Document as mshtml.HTMLDocument;
if (null != doc)
{
docState = doc.readyState;
}
};
App.Current.Dispatcher.Invoke(
DispatcherPriority.Normal,
getDocState);
if (null != doc)
{
while ((docState != "complete") && (docState != "interactive"))
{
// It should not take more than one or two iterations for the document to get loaded.
Thread.Sleep(100);
App.Current.Dispatcher.Invoke(
DispatcherPriority.Normal,
getDocState);
}
}
// DOC SHOULD BE LOADED AND READABLE NOW
// Go back to the UI thread to get more details
if (!App.Current.Dispatcher.HasShutdownStarted)
{
// This line is of your interest here
MessageBox.Show(doc.documentElement.innerHTML);
}
}
编辑:您可以在导航的事件处理程序中使用此代码。我等待doc加载代码的原因是,一旦WPF加载/导航完成,Web浏览器就会加载HTML和脚本等。这个脚本确保文档完全加载并处于可以与之交互的状态它。