При разборе HTML-страницы с использованием C# возникают проблемы

Я пытался что-то сделать, используя HtmlAgilityPack, Fizzler и Regular Expressions, но безуспешно.

Страница, которую я пытаюсь разобрать и разобрать, находится здесь http://www.sczg.unizg.hr/student-servis/vijest/2015-04-14-poslovi-u-administraciji/

Example of an item in item list:
<p> 
  <b>1628/ SomeBoldedTitle
  </b> 
    Some Description. 
    Some price 20,00kuna. 
  <strong>Contact somenumber
       098/1234-567 some mail
  </strong> 
</p>

Я хотел бы проанализировать этот элемент:

  • ИД 4/5>1628/ в элементе b
  • Title >SomeBoldedTitle в элементе b>
  • Описание> после / б
  • Контактный номер и ссылка> иногда в сильной> элемент иногда в б

Вот некоторый код, который я пытался получить хотя бы какой-то вывод, я ожидал, что все p элементы с b Но ничего не вышло.

 using System;
    using HtmlAgilityPack;
    using Fizzler.Systems.HtmlAgilityPack;

namespace Sample
{
    class Program
    {

        static void Main(string[] args)
        {
            var web = new HtmlWeb();
            var document = web.Load("http://www.sczg.unizg.hr/student-servis/vijest/2015-04-14-poslovi-u-administraciji/");
            var page = document.DocumentNode;
                foreach (var item in page.QuerySelectorAll("p.item"))
            {
                Console.WriteLine(item.QuerySelector("p:has(b)").InnerHtml);
            }
        }
    }
}

Вот ссылка на документацию fizzler, которую я использовал для получения этого кода https://fizzlerex.codeplex.com/

1 ответ

Вперед

Я рекомендую использовать модуль синтаксического анализа HTML, потому что HTML может привести к некоторым сумасшедшим крайним случаям, которые действительно искажают ваши данные. Но если вы контролируете свой исходный текст и по-прежнему хотите / должны использовать регулярные выражения, я предлагаю это возможное решение.

Описание

Учитывая следующий текст

Example of an item in item list:
<p> 
  <b>1628/ SomeBoldedTitle
  </b> 
    Some Description. 
    Some price 20,00kuna. 
  <strong>Contact somenumber
       098/1234-567 some mail
  </strong> 
</p>

Это регулярное выражение

<p>(?:(?!<p>).)*<b>([0-9]+)/\s*((?:(?!</b>).)*?)\s*</b>\s*((?:(?!<strong>|<b>).)*?)\s*<(?:strong|b)>\s*((?:(?!</).)*?)\s*</

Будет разбирать ваш текст на следующие группы захвата:

  • Группа 0 будет большая часть строки
  • Группа 1 будет многозначным кодом
  • Группа 2 будет названием
  • Группа 3 будет описание
  • Группа 4 будет номер телефона

Группы захвата

[0][0] = <p> 
  <b>1628/ SomeBoldedTitle
  </b> 
    Some Description. 
    Some price 20,00kuna. 
  <strong>Contact somenumber
       098/1234-567 some mail
  </
[0][1] = 1628
[0][2] = SomeBoldedTitle
[0][3] = Some Description. 
    Some price 20,00kuna.
[0][4] = Contact somenumber
       098/1234-567 some mail

Разъяснения

Визуализация регулярных выражений

Примечание: щелкните правой кнопкой мыши изображение и выберите вид в новом окне.

NODE                     EXPLANATION
----------------------------------------------------------------------
  <p>                      '<p>'
----------------------------------------------------------------------
  (?:                      group, but do not capture (0 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
      <p>                      '<p>'
----------------------------------------------------------------------
    )                        end of look-ahead
----------------------------------------------------------------------
    .                        any character
----------------------------------------------------------------------
  )*                       end of grouping
----------------------------------------------------------------------
  <b>                      '<b>'
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    [0-9]+                   any character of: '0' to '9' (1 or more
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  /                        '/'
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  (                        group and capture to \2:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
        </b>                     '</b>'
----------------------------------------------------------------------
      )                        end of look-ahead
----------------------------------------------------------------------
      .                        any character
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
  )                        end of \2
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  </b>                     '</b>'
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  (                        group and capture to \3:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
        <strong>                 '<strong>'
----------------------------------------------------------------------
       |                        OR
----------------------------------------------------------------------
        <b>                      '<b>'
----------------------------------------------------------------------
      )                        end of look-ahead
----------------------------------------------------------------------
      .                        any character
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
  )                        end of \3
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  <                        '<'
----------------------------------------------------------------------
  (?:                      group, but do not capture:
----------------------------------------------------------------------
    strong                   'strong'
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    b                        'b'
----------------------------------------------------------------------
  )                        end of grouping
----------------------------------------------------------------------
  >                        '>'
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  (                        group and capture to \4:
----------------------------------------------------------------------
    (?:                      group, but do not capture (0 or more
                             times (matching the least amount
                             possible)):
----------------------------------------------------------------------
      (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
        </                       '</'
----------------------------------------------------------------------
      )                        end of look-ahead
----------------------------------------------------------------------
      .                        any character
----------------------------------------------------------------------
    )*?                      end of grouping
----------------------------------------------------------------------
  )                        end of \4
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  </                       '</'
Другие вопросы по тегам