一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net WebBrowser操作网页代码

时间:2022-06-25 05:46:25 编辑:袖梨 来源:一聚教程网

使用fiddle截获post给服务器的url和数据,使用httprequest类代码post到服务器
今天给出另外一种方法,就是利用winform控件中的webbrowser控件来操作页面。

这里我们会模拟一个搜索过程,打开百度网站,输入搜索关键字,在搜索结果中打开连接

代码如下 复制代码
public form1()
{
initializecomponent();
(webbrowser1.activexinstance as shdocvw.webbrowser).navigatecomplete2 +=
new shdocvw.dwebbrowserevents2_navigatecomplete2eventhandler(form1_navigatecomplete2);
}
void form1_navigatecomplete2(object pdisp, ref object url)
{
ihtmldocument2 doc = (webbrowser1.activexinstance as shdocvw.webbrowser).document as ihtmldocument2;
doc.parentwindow.execscript("window.alert=null", "网页特效");
doc.parentwindow.execscript("window.confirm=null", "javascript");
doc.parentwindow.execscript("window.open=null", "javascript");
doc.parentwindow.execscript("window.showmodaldialog=null", "javascript");
doc.parentwindow.execscript("window.close=null", "javascript");
}


代码写到这里已经提交搜索了,webbrowser也会接收这次提交后的记过,下面我们需要在结果中打开一个连接做实验。
先查看一下搜索结果的html源代码

代码如下 复制代码
private void webbrowser1_documentcompleted(object sender, webbrowserdocumentcompletedeventargs e)
{
htmldocument doc = this.webbrowser1.document;
if(doc.url.absoluteuri=="")
{
doc.getelementbyid("kw").innertext = "翁玉礼";
doc.getelementbyid("su").invokemember("click");
}
if(doc.url.absoluteuri.contains("wd"))//根据url中的
{
htmlelement table = doc.getelementbyid("1");//根据搜索结果的html表,找到第一个搜索结果的url,这里模拟
var html = table.children[0].children[0].innerhtml;
var url = html.substring(html.indexof("href") + 6, html.indexof(" target"));
this.webbrowser1.navigate(url);
}
}

热门栏目