Preamble
我正在使用WebBrowser
控件,用户将与之交互,因此解决方案需要使用可见的WebBrowser
控制。
Question
如何检查某个元素是否有锚点作为子元素?所有浏览器都能够区分元素包含锚点(<a href=""...
),并提供“在新选项卡中打开”功能。这就是我试图复制的。但是,当我右键单击HtmlElement
我只能获取父元素。
Example
以 BBC 网站为例,当我右键单击突出显示的元素(下图)时,我的输出是DIV
,但是查看源代码有一个锚元素作为该元素的子元素div
.
SSCCE
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace BrowserLinkClick
{
public partial class Form1 : Form
{
private WebBrowser wb;
private bool firstLoad = true;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wb = new WebBrowser();
wb.Dock = DockStyle.Fill;
Controls.Add(wb);
wb.Navigate("http://bbc.co.uk");
wb.DocumentCompleted += wb_DocumentCompleted;
}
private void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == MouseButtons.Right)
{
HtmlElement element = wb.Document.GetElementFromPoint(PointToClient(MousePosition));
//I assume I need to check if this element has child elements that contain a TagName "A"
if (element.TagName == "A")
Debug.WriteLine("Get link location, open in new tab.");
else
Debug.WriteLine(element.TagName);
}
}
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (firstLoad)
{
wb.Document.MouseDown += new HtmlElementEventHandler(Document_MouseDown);
firstLoad = false;
}
}
}
}
请使用 BBC 网站和突出显示的标题测试任何建议的解决方案(标题发生变化,但 DOM 保持不变)。
你必须得到的子元素element
在检查它是否是锚点之前:
HtmlElement element = wb.Document.GetElementFromPoint(PointToClient(MousePosition));
foreach (HtmlElement child in element.Children)
{
if (child.TagName == "A")
Debug.WriteLine("Get link location, open in new tab.");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)