GeckoFx (3)使用 xpath 获取元素,生成 xpath 路径

GeckoFx (3)使用 xpath 获取元素,生成 xpath 路径

生成 xpath 需要使用 DomClick 事件,获取选中的元素对象。以下两个生成 xpath 的方法

/// 
/// 获取短 xpath
/// 
/// 
/// 
public string GetSmallXpath(GeckoNode node)
{
	if (node == null)
		return "";
	if (node.NodeType == NodeType.Attribute)
	{
		return String.Format("{0}/@{1}", GetSmallXpath(((GeckoAttribute)node).OwnerDocument), node.LocalName);
	}
	if (node.ParentNode == null)
	{
		return "";
	}
	string elementId = ((GeckoHtmlElement)node).Id;
	if (!String.IsNullOrEmpty(elementId))
	{
		return String.Format("//*[@id=\"{0}\"]", elementId);
	}
	int indexInParent = 1;
	GeckoNode siblingNode = node.PreviousSibling;
	while (siblingNode != null)
	{
		if (siblingNode.LocalName == node.LocalName)
		{
			indexInParent++;
		}
		siblingNode = siblingNode.PreviousSibling;
	}
	return String.Format("{0}/{1}[{2}]", GetSmallXpath(node.ParentNode), node.LocalName, indexInParent);
}
/// 
/// 获取长xpath
/// 
/// 
/// 
public string GetXpath(GeckoNode node)
{
	if (node == null)
		return "";
	if (node.NodeType == NodeType.Attribute)
	{
		return String.Format("{0}/@{1}", GetXpath(((GeckoAttribute)node).OwnerDocument), node.LocalName);
	}
	if (node.ParentNode == null)
	{
		return "";
	}
	int indexInParent = 1;
	GeckoNode siblingNode = node.PreviousSibling;
	while (siblingNode != null)
	{
		if (siblingNode.LocalName == node.LocalName)
		{
			indexInParent++;
		}
		siblingNode = siblingNode.PreviousSibling;
	}
	return String.Format("{0}/{1}[{2}]", GetXpath(node.ParentNode), node.LocalName, indexInParent);
}
获得元素,生成 xpath

/// 
/// 文档单击事件
/// 
/// 
/// 
void browser_DomClick(object sender, DomMouseEventArgs e)
{
	var ele = e.CurrentTarget.CastToGeckoElement();
	ele = e.Target.CastToGeckoElement();
	//短xpath
	var xpath1 = GetSmallXpath(ele);
	Msg("xpath1:" + xpath1);
	//长xpath
	var xpath2 = GetXpath(ele);
}

使用 xpath 查找元素

/// 
/// 通过 xpath 查找元素,btnXpath button 的点击事件
/// 
/// 
/// 
private void btnXpath_Click(object sender, EventArgs e)
{
	if (string.IsNullOrWhiteSpace(_xpath))
		return;
	var xresult = browser.DomDocument.EvaluateXPath(_xpath);
	var nodes = xresult.GetNodes();
	var elements = nodes.Select(x => x as GeckoElement).ToArray();
	var html = FindElement(elements);
}
//获得元素的 HTML 信息
private string FindElement(params GeckoElement[] nodes)
{
	if (nodes == null)
	{
		return "无匹配项...";
	}
	var html="";
	nodes.All(x =>
	{
		html = (x as GeckoHtmlElement).OuterHtml;
		return false;
	});
	return html;
}





你可能感兴趣的:(C#,开发资料料)