What is html agility pack

Html Agility Pack — удобный .NET парсер HTML

Всем привет!
Как-то раз мне пришла в голову идея проанализировать вакансии размещенные на Хабре. Конкретно интересовало, есть ли зависимость между размером зарплаты и наличия высшего образования. А еще сейчас у студентов идет сессия (в том числе и у меня), то возможно кому-то уже надоело трепать нервы на экзаменах и этот анализ будет полезен.
Так как я программист на .Net, то и решать эту задачу — парсить объявления на Хабре я решил на C#. Вручную разбирать строки html мне не хотелось, поэтому было придумано найти html-парсер, который помог бы осуществить задачу.
Забегая вперед скажу, что из анализа ничего интересного не вышло и сессию придется сдавать дальше 🙁
Но зато немножко расскажу про весьма полезную библиотеку Html Agility Pack

Выбор парсера

Вышел на эту библиотеку я через обсуждение на Stackoverflow. В комментариях предлагались еще решения, например библиотека SgmlReader, которая переводит HTML в XmlDocument, а для XML в .Net инструментов полный набор. Но почему-то меня это не подкупило и я пошел качать Html Agility Pack.

Читайте также:  Index php r site 2fentry

Беглый осмотр Html Agility Pack

Справку по библиотеке можно скачать на странице проекта. Функционал на самом деле очень радует.
Всего нам доступно двадцать основных классов:

Парсим хабр!

Вакансии на хабре представлены в виде таблицы, в строках дана информация о требуемой специальности и зарплате, но так как нам нужна информация об образовании, то придется переходить на страницу вакансии и разбирать ее.
Итак, начнем, нам нужна таблица, чтобы вытащить оттуда ссылки и инфу о позиции с зарплатой:

  1. static void GetJobLinks ( HtmlDocument html )
  2. var trNodes = html. GetElementbyId ( «job-items» ) . ChildNodes . Where ( x => x. Name == «tr» ) ;
  3. foreach ( var item in trNodes )
  4. var tdNodes = item. ChildNodes . Where ( x => x. Name == «td» ) . ToArray ( ) ;
  5. if ( tdNodes. Count ( ) != 0 )
  6. var location = tdNodes [ 2 ] . ChildNodes . Where ( x => x. Name == «a» ) . ToArray ( ) ;
  7. jobList. Add ( new HabraJob ( )
  8. Url = tdNodes [ 0 ] . ChildNodes . First ( ) . Attributes [ «href» ] . Value ,
  9. Title = tdNodes [ 0 ] . FirstChild . InnerText ,
  10. Price = tdNodes [ 1 ] . FirstChild . InnerText ,
  11. Country = location [ 0 ] . InnerText ,
  12. Region = location [ 2 ] . InnerText ,
  13. City = location [ 2 ] . InnerText
  14. > ) ;
  15. >
  16. >
  17. >

А после осталось пройти по каждой ссылке и вытащить инфу об образовании и заодно еще и занятость — здесь есть небольшая проблема в том, что если таблица с ссылками на вакансию лежала в div-е с известным id, то информация о вакансия лежит в таблице без всяких id, поэтому пришлось немножко поизвращаться:

  1. static void GetFullInfo ( HabraJob job )
  2. HtmlDocument html = new HtmlDocument ( ) ;
  3. html. LoadHtml ( wClient. DownloadString ( job. Url ) ) ;
  4. // html.LoadHtml(GetHtmlString(job.Url));
  5. // так делать нельзя 🙁
  6. var table = html. GetElementbyId ( «main-content» ) . ChildNodes [ 1 ] . ChildNodes [ 9 ] . ChildNodes [ 1 ] . ChildNodes [ 2 ] . ChildNodes [ 1 ] . ChildNodes [ 3 ] . ChildNodes . Where ( x => x. Name == «tr» ) . ToArray ( ) ;
  7. foreach ( var tr in table )
  8. string category = tr. ChildNodes . FindFirst ( «th» ) . InnerText ;
  9. switch ( category )
  10. case «Компания» :
  11. job. Company = tr. ChildNodes . FindFirst ( «td» ) . FirstChild . InnerText ;
  12. break ;
  13. case «Образование:» :
  14. job. Education = HabraJob. ParseEducation ( tr. ChildNodes . FindFirst ( «td» ) . InnerText ) ;
  15. break ;
  16. case «Занятость:» :
  17. job. Employment = HabraJob. ParseEmployment ( tr. ChildNodes . FindFirst ( «td» ) . InnerText ) ;
  18. break ;
  19. default :
  20. continue ;
  21. >
  22. >
  23. >

Результаты

Ну а дальше, сохраняем результаты в XML и смотрим в Excel-e, что же получилось… и видим, что ничего хорошего не получилось, потому что большинство компаний либо не указывают размер зарплаты, либо не указывают информацию об образовании (забывают, указывают в теле вакансии, или действительно неважно), либо не указывают все сразу.
Кому интересно, вот результаты в xlsx и xml, а здесь исходник

P.S.

При парсинге возникла такая проблема — страницы скачивались очень медленно. Поэтому я сначала попробовал WebClient, а потом WebRequest, но разницы не было. Поиск в гугле указал на то, что следует явно отключать Proxy в коде, и тогда все будет хорошо, однако это тоже не помогло.

Источник

Html Agility Pack (HAP) Html Agility Pack

What's Html Agility Pack?

HAP is an HTML parser written in C# to read/write DOM and supports plain XPATH or XSLT.

What's web scraping in C#?

What’s web scraping in C#?

Web scraping is a technique used in any language such as C# to extract data from a website.

Is web scraping legal?

That’s a gray zone! There is no official answer about it, and almost every company has some web scraping program. In short, do polite crawling and don’t spam a website and everything will be fine.

When is the v2.x coming?

When is the v2.x coming?

There is no official date, but the work is in progress. A lot of improvement is already planned to make web scraping even easier!

Which 3rd party libraries?

Which 3rd party libraries?

You can enhance HAP with some third party libraries:

Where can I find Html Agility Pack examples?

Where can I find Html Agility Pack examples?

Online examples are now available!

We need your help to support this Html Agility Pack!

Html Agility Pack is FREE and always will be.

However, last year alone, we spent over 3000 hours maintaining our free projects! We need resources to keep developing our open-source projects.

We highly appreciate any contribution!

> 3,000+ Requests answered per year

> $100,000 USD investment per year

> 500 Commits per year

> 100 Releases per year

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Html Agility Pack (HAP) is a free and open-source HTML parser written in C# to read/write DOM and supports plain XPATH or XSLT. It is a .NET code library that allows you to parse «out of the web» HTML files.

License

zzzprojects/html-agility-pack

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

What’s Html Agility Pack (HAP)?

It is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (No need to understand XPATH nor XSLT to use it, don’t worry. ). It is a .NET code library that allows you to parse «out of the web» HTML files. The parser is very tolerant of «real world» malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

Want to help us? Your donation directly helps us maintain and grow ZZZ Free Projects.

We can’t thank you enough for your support 🙏 .

Why should I contribute to this free & open-source library?

We all love free and open-source libraries! But there is a catch. nothing is free in this world.

We NEED your help. Last year alone, we spent over 3000 hours maintaining all our open source libraries.

Contributions allow us to spend more of our time on: Bug Fix, Development, Documentation, and Support.

How much should I contribute?

Any amount is much appreciated. All our free libraries together have more than 100 million downloads.

If everyone could contribute a tiny amount, it would help us make the .NET community a better place to code!

Another great free way to contribute is spreading the word about the library.

A HUGE THANKS for your help!

To view all our free and paid projects, visit our website.

About

Html Agility Pack (HAP) is a free and open-source HTML parser written in C# to read/write DOM and supports plain XPATH or XSLT. It is a .NET code library that allows you to parse «out of the web» HTML files.

Источник

Оцените статью