xpath表达式从链接中选择href值

时间:2015-03-05 13:20:25

标签: c# visual-studio-2012 xpath

我有这样的HTML代码

<a class="cat" href="/Home/txtdata0/">txtdata0</a>
<a class="cat" href="/Home/txtdata1/">txtdata1</a>
<a class="cat" href="/Home/txtdata2/">txtdata2</a>
<a class="cat" href="/Home/txtdata3/">txtdata3</a>

访问我使用此类XPATH的链接的所有文本(如在C#中的Visual Studio中)

.//a[@class=\"cat\"]

访问链接的所有href值我使用这样的XPATH(如在C#中的Visual Studio中)

.//a[@class=\"cat\"]/@href

Google Chrome Xpath助手秀( .// [@class =&#34; cat&#34;] .// a [@class =&#34; cat& #34;] / @ href )结果都正确

txtdata0
txtdata1
txtdata2
txtdata3

/Home/txtdata0/
/Home/txtdata1/
/Home/txtdata2/
/Home/txtdata3/

Visual Studio有这样的Xpath .// a [@class = \&#34; cat \&#34;] 显示:

txtdata0
txtdata1
txtdata2
txtdata3

并使用这样的Xpath .// [@class = \&#34; cat \&#34;] / @ href 显示:

txtdata0
txtdata1
txtdata2
txtdata3

为什么第二个输出与第一个输出相同?

程序代码

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(seturl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
    Stream receiveStream = response.GetResponseStream();
    StreamReader readStream = null;

    if (response.CharacterSet == null)
    {
        readStream = new StreamReader(receiveStream);
    }
    else
    {
        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
    }

    data = readStream.ReadToEnd();

    response.Close();
    readStream.Close();
}

doc.LoadHtml(data);

HtmlAgilityPack.HtmlNodeCollection bodynode = doc.DocumentNode.SelectNodes(".//a[@class=\"cat\"]");
HtmlAgilityPack.HtmlNodeCollection bodynod = doc.DocumentNode.SelectNodes(".//a[@class=\"cat\"]/@href");
MessageBox.Show(bodynode.Count.ToString());
MessageBox.Show(bodynod.Count.ToString());

for (int i = 0; i < bodynode.Count; i++)
{
    MessageBox.Show(bodynode[i].InnerText.ToString() + " - " + bodynod[i].InnerText.ToString());
}

1 个答案:

答案 0 :(得分:2)

如果我没记错的话,可以像这样提取HAP属性

 string _tmpUrl = documentUrl.DocumentNode.SelectNodes("//a[@class='cat']")[i].Attributes["href"].Value;