c# - HTML 敏捷包 : parsing an href tag

标签 c# asp.net-mvc-3 html-parsing html-agility-pack

我如何从中有效地解析 href 属性值:

<tr>
<td rowspan="1" colspan="1">7</td>
<td rowspan="1" colspan="1">
<a class="undMe" href="/ice/player.htm?id=8475179" rel="skaterLinkData" shape="rect">D. Kulikov</a>
</td>
<td rowspan="1" colspan="1">D</td>
<td rowspan="1" colspan="1">0</td>
<td rowspan="1" colspan="1">0</td>
<td rowspan="1" colspan="1">0</td>
[...]

我对播放器 ID 很感兴趣,它是:8475179 这是我目前拥有的代码:

        // Iterate all rows (players)
        for (int i = 1; i < rows.Count; ++i)
        {
            HtmlNodeCollection cols = rows[i].SelectNodes(".//td");

            // new player
            Dim_Player player = new Dim_Player();

                // Iterate all columns in this row
                for (int j = 1; j < 6; ++j)
                {
                    switch (j) {
                        case 1: player.Name = cols[j].InnerText;
                                player.Player_id = Int32.Parse(/* this is where I want to parse the href value */); 
                                break;
                        case 2: player.Position = cols[j].InnerText; break;
                        case 3: stats.Goals = Int32.Parse(cols[j].InnerText); break;
                        case 4: stats.Assists = Int32.Parse(cols[j].InnerText); break;
                        case 5: stats.Points = Int32.Parse(cols[j].InnerText); break;
                    }
                }

最佳答案

根据您的示例,这对我有用:

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.Load("test.html");
var link = htmlDoc.DocumentNode
                  .Descendants("a")
                  .First(x => x.Attributes["class"] != null 
                           && x.Attributes["class"].Value == "undMe");

string hrefValue = link.Attributes["href"].Value;
long playerId = Convert.ToInt64(hrefValue.Split('=')[1]);

要真正使用你需要添加错误检查等。

关于c# - HTML 敏捷包 : parsing an href tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8497673/

相关文章:

c# - 使用正则表达式获取html标签的变量值

java - HTMLUnit:获取没有名称、id 的按钮,仅键入 onclick=

c# - 寻找 `protected override void Dispose(bool disposing)` 的 Stylecop 完美评论

c# - 在 C# 中从 MYSQL 中读取 Mediumblob 数据类型

c# - 如何区分两个同名的 .snk 文件?

asp.net - MVC ASP.NET - 手动授权某人并通过表单例份验证保留授权

c# - 查看模型将空属性发回 Controller

javascript - 使用 async 和 defer 按顺序加载脚本

c# - Entity Framework 中的数据库错误处理

javascript - 处理Div标签运行时添加的按钮的点击事件