【问题标题】:Get the number of an href url parameter from downloaded html page?从下载的html页面获取href url参数的数量?
【发布时间】:2010-11-13 16:19:45
【问题描述】:

我正在尝试从 href 中的 url 参数获取 ID,如下所示:

<a href="http://www.mysite.com/myitem.php?id=71312">MyItemName</a>

我只想要 71312,目前我正在尝试使用正则表达式(但如果你有更好的方法,我很乐意尝试):

        string html,itemID;
        using (var client = new WebClient())
        {
            html = client.DownloadString("http://www.mysite.com/search.php?search_text=" + myItemName);
        }

        string pattern = "<a href=\"http://www.mysite.com/myitem.php?id=(\d+)\">" + myItemName + "</a>";
        Match m = Regex.Match(html, pattern, RegexOptions.IgnoreCase);
        if (m.Success)
        {
            itemID = m.Groups[1].Value;
            MessageBox.Show(itemID);
        }

html 示例:

more html body
<h1>Items - List</h1>
<p><a href="http://www.mysite.com/myitem.php?id=12313">MyItemNameTest</a>, <a href="http://www.mysite.com/myitem.php?id=83">MyItemNameTestB</a>, <a href="http://www.mysite.com/myitem.php?id=213784">MYItemNameOther</a></p>

</div>
more html body

【问题讨论】:

    标签: c# regex html-parsing


    【解决方案1】:

    显示你的正则表达式出错的地方:

    . 和 ? 是正则表达式中的特殊字符。 . 表示“任何字符”,? 表示“前一个表达式出现零次或一次”。因此,您的正则表达式无法匹配。此外,您需要在 C# 中使用逐字字符串(除非您想转义每个反斜杠):

    @"<a href=\"http://www\.mysite\.com/myitem\.php\?id=(\d+)\">" + myItemName + "</a>";
    

    可能会起作用。

    也就是说,除非您检查的所有链接都完全遵循这种格式,否则您可能会遇到问题。在 SO 上使用正则表达式解析 HTML 会引起 Cthulhu 的愤怒。

    【讨论】:

      【解决方案2】:

      用途:

      Uri u = new Uri("http://www.mysite.com/myitem.php?id=12313");
      string s = u.Query;
      HttpUtility.ParseQueryString(s).Get("id");
      

      在变量id 中有编号。找出函数的其余部分:)

      【讨论】:

      • 谢谢,但我需要从 html 中解析它,而不是从将要发送的字符串中解析。
      猜你喜欢
      • 1970-01-01
      • 2012-06-23
      • 2018-03-29
      • 2018-08-27
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多