0

大家好,我有字符串<span class="lnk">Участники&nbsp;<span class="clgry">59728</span></span> 我解析它

string population = Regex.Match(content, @"Участники&nbsp;<span class=""clgry"">(?<id>[^""]+?)</span>").Groups["id"].Value;
int j = 0;
if (!string.IsNullOrEmpty(population))
{
    log("[+] Группа: " + group + " Учасники: " + population + "\r\n");
    int population_int = Convert.ToInt32(population);
    if (population_int > 20000)
    {
        lock (accslocker)
        {
        StreamWriter file = new StreamWriter("opened.txt", true);
        file.Write(group + ":" + population + "\r\n");
        file.Close();
    }
    j++;
}

}

但是当我的字符串是><span class="lnk">Участники&nbsp;<span class="clgry"></span></span>我收到一个扩展“输入字符串的格式不正确”。如何避免?

4

2 回答 2

2

代替 Regex 使用真正的 html 解析器来解析 html。(例如,HtmlAgilityPack

string html = @"<span class=""lnk"">Участники&nbsp;<span class=""clgry"">59728</span>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

var list = doc.DocumentNode.SelectNodes("//span[@class='lnk']/span[@class='clgry']")
              .Select(x => new
              {
                  ParentText = x.ParentNode.FirstChild.InnerText,
                  Text = x.InnerText
              })
              .ToList();
于 2012-12-16T13:28:09.393 回答
1

尝试使用正则表达式解析 html 内容并不是一个好的决定。看到这个。请改用Html Agliliy Pack

var spans = doc.DocumentNode.Descendants("span")
               .Where(s => s.Attributes["class"].Value == "clgry")
               .Select(x => x.InnerText)
               .ToList();
于 2012-12-16T13:47:42.447 回答