我在StackOverflow上看到了关于这个主题的几个主题,但是它们似乎都没有提供答案。
我有一个按钮,当点击它时,会打开一个不可见的网页,导航到一个URL,将信息输入一个框,按一个按钮,然后抓取屏幕以获取信息。
我的代码的骨骼基本上都在点击:
WebBrowser wb = new WebBrowser;
wb.Visibility = System.Windows.Visibility.Hidden;
wb.Navigate("http://somepage.com");
这就是它变得棘手的地方。
我正在寻找一种方法确保在尝试输入数据或刮擦屏幕之前加载页面。我看过几个讨论Navigated
,IsLoaded
,LoadCompleted
以及BackgroundWork
内容的主题,但是我无法让这些内容发挥作用。
哪个是用于确定页面已完全加载的最佳选项?你如何让所选择的方法起作用?
我也无法从屏幕上获取数据,因为WPF不使用相同的GetElementByID
。
修改
根据以下评论,以下是我遇到的错误:
IsLoaded
永远不会返回true
private void GetData_Click(object sender, RoutedEventArgs e)
{
int x=0;
HTMLDocument doc;
wb = new WebBrowser();
wb.Visibility = System.Windows.Visibility.Visible;
wb.Navigate("somesite.com");
doc = wb.Document as mshtml.HTMLDocument;
while(!wb.IsLoaded)
{
//Wait
}
doc.getElementById("txt_One").innerText = "It Worked";
}
将其置于无限循环中,因为wb
似乎无法加载。
事件'System.Windows.Controls.WebBrowser.LoadCompleted'只能出现在+ =或 - =
的左侧
private void GetData_Click(object sender, RoutedEventArgs e)
{
int x=0;
HTMLDocument doc;
wb = new WebBrowser();
wb.Visibility = System.Windows.Visibility.Visible;
wb.Navigate("somesite.com");
doc = wb.Document as mshtml.HTMLDocument;
wb.LoadCompleted += wb_LoadCompleted;
doc.getElementById("txt_One").innerText = "It Worked";
}
void wb_LoadCompleted(object sender, NavigationEventArgs e)
{
}
产生错误
{filename}
中出现未处理的“System.NullReferenceException”类型异常附加信息:未将对象引用设置为对象的实例。
答案 0 :(得分:7)
webbrowser控件有一个loadedevent(你有): LoadCompleted:当dom完全加载时触发。
绑定事件并在事件方法中获取文档而不是立即。
//root is a grid element identified in the XAML
public WebBrowser webb;
public MainWindow()
{
InitializeComponent();
webb = new WebBrowser();
webb.Visibility = System.Windows.Visibility.Hidden;
root.Children.Add(webb);
webb.LoadCompleted += webb_LoadCompleted;
webb.Navigate("http://www.google.com");
}
void webb_LoadCompleted(object sender, NavigationEventArgs e)
{
MessageBox.Show("Completed loading the page");
mshtml.HTMLDocument doc = webb.Document as mshtml.HTMLDocument;
mshtml.HTMLInputElement obj = doc.getElementById("gs_taif0") as mshtml.HTMLInputElement;
mshtml.HTMLFormElement form = doc.forms.item(Type.Missing, 0) as mshtml.HTMLFormElement;
webb.LoadCompleted -= webb_LoadCompleted; //REMOVE THE OLD EVENT METHOD BINDING
webb.LoadCompleted += webb_LoadCompleted2; //BIND TO A NEW METHOD FOR THE EVENT
obj.value = "test search";
form.submit(); //PERFORM THE POST ON THE FORM OR SEARCH
}
//SECOND EVENT TO FIRE AFTER YOU POST INFORMATION
void webb_LoadCompleted2(object sender, NavigationEventArgs e)
{
MessageBox.Show("Completed loading the page second time after post");
}
您需要将doc = wb.Document作为mshtml.HTMLDocument;在loadcompleted事件中。因为在加载完成之前,您无法获取文档。