我有一个div中有两个链接的网站。 我想点击该div内的第二个链接。 以下是网站HTML的外观:
<div class="title-nav-single">
<strong></strong>
<a href="http://www.website.com/50665">Previous</a>
<a href="http://www.website.com/50665/3">Next</a>
</div>
现在,我尝试点击包含Next
的链接。我不想获得链接href
值,我只想点击链接。这是我到目前为止所尝试的:
private void button1_Click(object sender, EventArgs e)
{
string xpath = GetJsSingleXpathString("//DIV[@ID=\"outbrain_widget_0\"]/preceding-sibling::DIV[3]//A[normalize-space()=\"Next\"]");
JsFireEvent(xpath, "click");
// webcontrol.ExecuteJavascriptWithResult("document.getElementsByClassName('title-nav-single').ElementAt(1).DomObject.click();");
}
public static string GetJsSingleXpathString(string xpath)
{
return String.Format("document.evaluate(\"{0}\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue", xpath);
}
// executes javascript which fires specified event on element
// Example: JsFireEvent("document.getElementById('my_id')", "click");
public void JsFireEvent(string getElementQuery, string eventName)
{
webcontrol.ExecuteJavascript(@"function fireEvent(element,event) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
element.dispatchEvent(evt);
}" + String.Format("fireEvent({0}, '{1}');", getElementQuery, eventName));
}
}
答案 0 :(得分:1)
要检测是否点击了链接,您需要添加target="_blank"
:
<a href="http://www.website.com/50665/3" target="_blank">Next</a>
并捕获此事件:
webControl.ShowCreatedWebView += OnShowNewView;
internal static void OnShowNewView( object sender, ShowCreatedWebViewEventArgs e )
{
// Do sth with your link. it's in e.TargetURL
}
最后,你可以用传统方式打开它:
System.Diagnostics.Process.Start(e.TargetURL.ToString());
..或做任何你想做的事情。您可以找到更多信息here