0

Hi guys I have string <span class="lnk">Участники&nbsp;<span class="clgry">59728</span></span> I parse it

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++;
}

}

But when my string is ><span class="lnk">Участники&nbsp;<span class="clgry"></span></span> I receive an exaption "Input string was not in a correct format". How to avoid it?

2 Answers2

2

Instead of Regex use a real html parser to parse htmls. (for ex, 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();
L.B
  • 114,136
  • 19
  • 178
  • 224
1

Trying to parse html content with regex is not a good decision. See this. Use Html Agliliy Pack instead.

var spans = doc.DocumentNode.Descendants("span")
               .Where(s => s.Attributes["class"].Value == "clgry")
               .Select(x => x.InnerText)
               .ToList();
Community
  • 1
  • 1
I4V
  • 34,891
  • 6
  • 67
  • 79