i'm trying scrap pages c# using webbrowser control.
in order have information scrap have click span element has onclick event.
this span looks like:
<span title="title" class="class" onclick="somefunction(value);"></span> this code:
foreach (htmlelement span in table.getelementsbytagname("span")) { span.invokemember("click"); } its simple , reason doesn't anything. have tried evaluate code , result getting null.
any idea how invoke click?
this example .net 4.5 , wpf adjusted fit winform webbrowser control. assume html page looks this:
<html> <head> <script> function somefunction(value){ alert("clicked on: " + value); } </script> </head> <body> <span title="title" class="class" onclick="somefunction('span_01');">blah blah blah</span> <span title="title" class="class" onclick="somefunction('span_02');">blah blah blah</span> <span title="title" class="class" onclick="somefunction('span_03');">blah blah blah</span> </body> </html> and have usercontrol wrapping webbrowser control (xaml below)
<usercontrol x:class="webbrowserexample.webbrowseradapter" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:ignorable="d" d:designheight="300" d:designwidth="300"> <grid> <webbrowser x:name="webbrowsercontrol"></webbrowser> </grid> </usercontrol> then possible solution inject page javascript function want , call .net. add following methods webbrowseradapter class:
void webbrowseradapter_loaded(object sender, routedeventargs e) { webbrowsercontrol.loadcompleted += webbrowsercontrol_loadcompleted; webbrowsercontrol.navigate("http://localhost:9080/console/span.html"); } void webbrowsercontrol_loadcompleted(object sender, navigationeventargs e) { incjectclickonspanelementscript(); } private void incjectclickonspanelementscript() { string script = @" function triggerclicksonspan(){ var spans = document.getelementsbytagname('span'); for(var = 0; < spans.length; i++){ spans[i].click(); } }"; injectscript(script); webbrowsercontrol.invokescript("triggerclicksonspan"); } public void injectscript(string scripttext) { htmldocument htmldocument = (htmldocument)webbrowsercontrol.document; var headelements = htmldocument.getelementsbytagname("head"); if (headelements.length == 0) { throw new indexoutofrangeexception("no element tag 'head' has been found in document"); } var headelement = headelements.item(0); ihtmlscriptelement script = (ihtmlscriptelement)htmldocument.createelement("script"); script.text = scripttext; headelement.appendchild(script); } you need add microsoft.mshtml among references of project. please note that, in simplified example, the script injected every time page gets loaded. imagine need tweak code adapt needs
Comments
Post a Comment