我需要有关使用Web浏览器的帮助
问题描述:
我使用网页浏览器,我可以导航到网站,但我无法像文本框那样更改元素值。
i使用此代码填写谷歌文本框和点击搜索按钮:
i use web browser,i can navigate to site but i can't change elements value like text boxes.
i use this code to fill google text box and click on search button:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("google.com");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_h);
}
private void web_h(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
b.Document.GetElementById("gbqfq").InnerText = "programming";
b.Document.GetElementById("gbqfba").InvokeMember("click");
}
但我遇到这个错误:System.NullReferenceException
你能帮我吗? ?
but i face with this error: System.NullReferenceException
can you help me?
答
你在线上获得错误
b.Document.GetElementById("gbqfq").InnerText = "programming";
这是因为没有名为 gbqfq
的元素所以
b.Document.GetElementById("gbqfq")
为空。
您无法为null对象的属性(例如 .InnerText
)赋值。
您需要先检查成功,例如
is null.
You can't assign values to properties (e.g. .InnerText
) of null objects.
You need to check for success find first e.g.
private void web_h(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
HtmlElement h1 = b.Document.GetElementById("gbqfq");
if (h1 != null)
h1.InnerText = "programming";
h1 = b.Document.GetElementById("gbqfba");
if (h1 != null)
h1.InvokeMember("click");
}