有很多不同的方法可以实现此功能。然而,我的猜测是:
- 导航到下一页的调用发生得太快,或者
- The
Document.Completed
登录后事件未正确触发(这种情况很常见,尤其是在目标文档包含动态脚本的情况下)
我已经完成了很多网页自动化(从一个链接导航到另一个链接,然后执行一些操作,然后导航到另一个链接等),您应该考虑使用异步进程。原则上,处理问题时可能总是最好的webBrowser
反对使用异步进程,仅仅是因为在许多情况下,您需要在执行其他功能时运行一个进程。
无需过多讨论,请查看此问题的答案并研究代码:WebBrowser Navigate 和 InvokeScript 的流程 https://stackoverflow.com/questions/18280487/flow-of-webbrowser-navigate-and-invokescript
但是,在尝试该实现之前,您可以简单地尝试在尝试导航到该页面之前添加异步等待。 (异步等待类似于Thread.Sleep()
,但实际上并没有停止页面的加载,即“线程”)。
(以前从未听说过异步进程?查看MSDN 上的这个教程 https://msdn.microsoft.com/en-us/library/hh191443.aspx).
首先尝试这个:
static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (wb.Url.ToString().IndexOf("login.aspx") > -1)
{
wb.Document.GetElementById("txtnumber").SetAttribute("value", "000001");
wb.Document.GetElementById("txtUserName").SetAttribute("value", "myusername");
wb.Document.GetElementById("txtPassword").SetAttribute("value", "mypassword");
wb.Document.GetElementById("btnLogin").InvokeMember("click");
}
else
{
//wb.Document.Body you are logged in do whatever you want here.
await Task.Delay(1000); //wait for 1 second just to let the WB catch up
wb.Navigate("https://www.thewebsiteiwanttogo.com/product.aspx");
Console.WriteLine(wb.DocumentText);
Console.ReadLine();
Application.Exit();
}
}
如果这没有帮助,请考虑上面的链接 https://stackoverflow.com/questions/18280487/flow-of-webbrowser-navigate-and-invokescript并尝试使用异步进程实现更强大的导航序列。
如果这不起作用,并且您需要一些导航或等待动态页面加载的帮助,请尝试这篇文章:如何使用.NET的WebBrowser或mshtml.HTMLDocument动态生成HTML代码? https://stackoverflow.com/questions/20930414/how-to-dynamically-generate-html-code-using-nets-webbrowser-or-mshtml-htmldocu/20934538#20934538我已经多次使用过这种代码神学,而且效果很好。
希望这些方法之一有帮助!让我知道,我可以帮助您生成一些更具体的代码片段。
EDIT:
乍一看,我会猜测Console.ReadLine()
将会冻结导航wb.Navigate("https://www.thewebsiteiwanttogo.com/product.aspx");
,因为它不会立即发生。您可能想要添加另一个if
中的声明Document.Completed
处理程序允许wb.Navigate("https://www.thewebsiteiwanttogo.com/product.aspx");
在尝试抓取之前完成导航wb.DocumentText
。例如:
static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (wb.Url.ToString().IndexOf("login.aspx") > -1)
{
wb.Document.GetElementById("txtnumber").SetAttribute("value", "000001");
wb.Document.GetElementById("txtUserName").SetAttribute("value", "myusername");
wb.Document.GetElementById("txtPassword").SetAttribute("value", "mypassword");
wb.Document.GetElementById("btnLogin").InvokeMember("click");
}
else if(wb.Url.ToString().IndexOf("product.aspx") > -1)
{
Console.WriteLine(wb.DocumentText);
Console.ReadLine();
Application.Exit();
}
else
{
//wb.Document.Body you are logged in do whatever you want here.
await Task.Delay(1000); //wait for 1 second just to let the WB catch up
wb.Navigate("https://www.thewebsiteiwanttogo.com/product.aspx");
}
}