在webbrowser控件中执行javascript

时间:2013-06-22 03:31:33

标签: c# javascript html dom

我正在尝试通过在页面上执行javascript来解析谷歌搜索结果列表中的链接,这通常会在您单击链接时解析。基本上,我试图在页面加载时解决所有问题。

这是google为前两个搜索结果生成的html:

<H2 class=hd>Search Results</H2>
<DIV id=ires>
<OL id=rso eid="3gHFUYToG6LD0gGJ2IDAAQ">
<LI class=g>
<DIV class=rc data-hveid="43"><SPAN style="FLOAT: left"></SPAN>
<H3 class=r><A onmousedown="return rwt(this,'','','','1','AFQjCNH7JvhrnBRwX-7DKsGJZoasX9zqFA','','0CCwQFjAA','','',event)" href="http://prezi.com/wnx5jat2oene/ipad/">IPad by <EM>Frunk La Je</EM> on Prezi</A></H3>
<DIV class=s>
<DIV>
<DIV style="WHITE-SPACE: nowrap" class="f kv"><CITE>prezi.com/wnx5jat2oene/ipad/</CITE>‎
<DIV class="action-menu ab_ctl"><A aria-haspopup=true aria-expanded=false id=am-b0 class="clickable-dropdown-arrow ab_button" role=button href="#" jsaction="ab.tdd; keydown:ab.hbke; keypress:ab.mskpe" data-ved="0CC0Q7B0wAA" aria-label="Result details"><SPAN class=mn-dwn-arw></SPAN></A>
<DIV class="action-menu-panel ab_dropdown" role=menu tabIndex=-1 jsaction="keydown:ab.hdke; mouseover:ab.hdhne; mouseout:ab.hdhue" data-ved="0CC4QqR8wAA">
<UL>
<LI class="action-menu-item ab_dropdownitem" role=menuitem><A class=fl onmousedown="return rwt(this,'','','','1','AFQjCNHsvjmPpYAOeqVOHIIs_PWPuD5JaQ','','0CC8QIDAA','','',event)" href="http://webcache.googleusercontent.com/search?q=cache:bKCj-2ogWdIJ:prezi.com/wnx5jat2oene/ipad/+frunk+la+je&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us">Cached</A></LI></UL></DIV></DIV></DIV>
<DIV class="f slp"></DIV><SPAN class=st>IPad. No description. by <EM>Frunk La Je</EM> on 7 June 2012 4 Tweet <B>...</B> thanks&lt;/a&gt;&lt;/p&gt;. Make a copy Share Embed Like. by <EM>Frunk La Je</EM> on 7 June 2012 4.</SPAN></DIV></DIV></DIV></LI>
<LI class=g>
<DIV class=rc data-hveid="48"><SPAN style="FLOAT: left"></SPAN>
<H3 class=r><A onmousedown="return rwt(this,'','','','2','AFQjCNE7-nvy-ymTrBI0x4zleJOUXlY6nA','','0CDEQFjAB','','',event)" href="http://prezi.com/user/q53evqg1dnrn/"><EM>Frunk La Je</EM> on Prezi</A></H3>
<DIV class=s>

解析第一个链接的函数:

onmousedown="return rwt(this,'','','','1','AFQjCNH7JvhrnBRwX-7DKsGJZoasX9zqFA','','0CCwQFjAA','','',event)"

我试过了:

    foreach (HtmlElement h in web.Document.All)
    {
        h.RaiseEvent("onmousedown");
    }

我尝试用“MouseDown”替换“onmousedown”。

我也试过了:

web.Document.InvokeScript("rwt(this,'','','','1','AFQjCNH7JvhrnBRwX-7DKsGJZoasX9zqFA','','0CCwQFjAA','','',event)");

我有什么想法可以让这个函数执行?我也查看了getElementByID函数,但我不知道ID是什么。

2 个答案:

答案 0 :(得分:1)

尝试以编程方式模拟点击,让我们在您的一个anchor tag <a>中说。现在使用您自己的代码,我们将模拟您first anchor tag的{​​{1}}点击(如下所示),如下所示:

subscript 0

答案 1 :(得分:1)

HtmlDocument doc = browser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text","function sayhello() { alert('hello'); }");
head.AppendChild(s);
browser.Document.InvokeScript("sayHello");