Get XPath from clicked HtmlElement in WebBrowserControl

前端 未结 1 1665
情书的邮戳
情书的邮戳 2021-01-14 08:54

How can I get the XPath from a clicked HtmlElement in the WebBrowserControl?

This is how I retrieve the clicked HtmlElement:

System.Windows.Forms.Htm         


        
相关标签:
1条回答
  • XPath expression is not a standard feature of HTML (unlike with XML). If you're looking to get an element XPath which you can later use with Html Agility Pack, you have at least two options:

    1. Walk up the element's DOM ancestry tree using HtmlElement.Parent and construct the XPath manually.

    2. Use Html Agility Pack itself and do something like this (untested):

    HtmlElement element = this.webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition);
    
    var savedId = element.Id;
    var uniqueId = Guid.NewGuid().ToString();
    element.Id = uniqueId;
    
    var doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(element.Document.GetElementsByTagName("html")[0].OuterHtml);
    element.Id = savedId;
    
    var node = doc.GetElementbyId(uniqueId);
    var xpath = node.XPath;
    
    0 讨论(0)
提交回复
热议问题