Xpath Web刮

时间:2014-11-26 01:39:17

标签: c# xpath html-agility-pack

<a class="support" style="letter-spacing: -1px" href="/support/index.php?/Knowledgebase/List/updates" data-executing="0">I'm random</a>    

我正在尝试使用xpath抓取上面的链接属性,链接文本"I'm random"总是在变化。其余的保持不变。 "I'm random"文本正是我想要的。

我真的不懂xpath,我怎样才能拉出内部文本?我试过了:

string html = Web.ExecuteJavascriptWithResult("document.getElementsByTagName('html')[0].innerHTML");
var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(html);
var Attributes = new List<string>();
var Randomtxt = htmlDoc.DocumentNode.SelectNodes("//a[‌​@href]");
if (Randomtxt != null)
{
    foreach (var contents in Randomtxt)
    {
        string href = contents.InnerHtml;
        var parts = href.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length > 1)
        {
            Attributes.Add(parts[1]);
        }
    }
    Attribute.DataSource = Attributes;
}    

但它什么都没有回报。我如何才能获得内在文本。

2 个答案:

答案 0 :(得分:1)

不是xpath,但这适用于我想做的事情,问题解决了。

    List<string> Attributes = new List<string>();
    string html = Web.ExecuteJavascriptWithResult("document.getElementsByTagName('html')[0].innerHTML");
    MatchCollection m1 = Regex.Matches(html, @"data-executing=\s*(.+?)\s*/a>", RegexOptions.Singleline);

    foreach (Match m in m1)
     {
      string new = m.Groups[1].Value;
      Attributes.Add(new);
     }
    Attribute.DataSource = Attributes;

答案 1 :(得分:0)

首先找到单个节点

var Randomtxt = htmlDoc.DocumentNode.SelectSingleNode(&#34; // * [@class =&#39; support&#39;]&#34;);

然后拉内部文本

string value = Randomtxt.Innertext;