Как парсить xml python
Перейти к содержимому

Как парсить xml python

Основы парсинга с помощью Python+lxml

Добрый день, уважаемые читатели.
В сегодняшней статье я покажу основы разбора HTML разметки страниц с помощью библиотеки lxml для Python.
Если вкратце, то lxml это быстрая и гибкая библиотека для обработки разметки XML и HTML на Python. Кроме того, в ней присутствует возможность разложения элементов документа в дерево. В статье я постараюсь показать, насколько просто ее применение на практике.

Выбор цели для парсинга

Т.к. я активно занимаюсь спортом, в частности БЖЖ мне захотелось посмотреть статисту по болевым приемам во все проведенных турнирах мировых турнирах по MMA.
Поиски по гулу привели меня на сайт со всей официальной статистикой по крупным международным турнирам по смешанным единоборствам. Единственной загвоздкой было то, что информация на нам была представлена в неудобном для анализа виде. Это связано с тем, что результаты турниров находится отдельных страницах. Кроме того, дата турнира также с его названием вынесены на отдельную страницу отдельной странице.
Чтобы объединить всю информацию по турнирам в одну таблицу, пригодную для анализа, было принято решение написать парсер описанный ниже.

Алгоритм работы парсера

  1. За основу возьмем таблицу со всеми турнирами и их датами, которая находится
    по данному
    адресу
  2. Занесем данные с этой страницы в набор данных, cо следующими столбцами:
  3. турнир
  4. ссылка на описание
  5. дата
  6. По каждой записи набора (по каждому турниру) осуществляем переход по полю
    [ссылка на описание], для получения информации о боях
  7. Записываем информацию по всем боям турнира
  8. К набору данных с информацией о боях добавляем дату проведения турнира из
    набора (2)

Начало работы с lxml

Для работы нам понадобятся модули lxml и pandas. Подгрузим их в нашу программу:

Для удобства дальнейшего парсинга вынесем основной домен в отдельную переменную:

Теперь давайте получим объект для парсинга. Сделать это можно с помощью функции parse():

Теперь откроем указанную таблицу в HTML редакторе и изучаем ее структуру. Больше всего нас интересует блок с классами events_table data_table row_is_link , т.к. именно он содержит таблицу с нужными нам данными. Получить данный блок можно так:

Разберемся, что делает данный код.
Сначала с помощью функции getroot() мы получаем корневой элемент нашего документа (это нужно для последующей работы с документом).
Далее, с помощью функции find_class() мы находим все элементы с указанными классами. В результате работы функции мы получим список таких элементов. Т.к. после визуального анализа HTML кода страницы видно, что по данному критерию подходит только один элемент, то мы извлекаем его из списка с помощью функции pop().
Теперь надо получить таблицу из нашего div‘a, полученного ранее. Для этого воспользуемся методом getchildren(), который возвращает список подчерненных объектов текущего элемента. И
потому, что у нас только один такой объект, ты мы извлекаем этот его из списка.

Теперь переменная t содержит таблицу с необходимой для нас информацией. Теперь, я получу 2 вспомогательных dataframe’a, объединив которые, мы получим данные о турнирах с датами их проведения и ссылками на результаты.
В первый набор я включу все названия турниров и ссылки на их страницы на сайте. Это легко сделать с помощью итератора iterlinks(), который возвращает список котрежей (элемент, атрибут,
адрес ссылки, позиция ) внутри заданного элемента. Собственно, из этого кортежа, нам нужен адрес ссылки и ее текст.
Тест ссылки можно получить обративший к свойству .text соответсвующего элемента. Код будет следующим:

Внимательный читатель заметит, что в цикле мы исключаем первые 5 записей. В них содержится не нужная нам информация, типа заголовков полей, поэтому я от них и избавился.
Итак, ссылки мы получили. Теперь получим 2 поднабор данных с датами проведения турниров. Это можно сделать так:

В коде, показанном выше, мы проходим по всем строкам (теги tr) в таблице t. Затем для каждой строки получаем список дочерних колонок (элементы td). И получаем информацию записанную в первой и второй колонках с помощью метода text_content, который возвращает строку из текста всех дочерних элементов данного столбца.
Чтобы понять, как работает метод text_content приведем небольшой пример. Допустим у нас задана такая структура документа <tr><td><span>текст</span><span>текст</span>. Так вот, метод text_content вернет строку текст текст, а метод text не вернет ничего, или же просто текст.

Теперь, когда у нас есть 2 поднабора данных, объединим их в итоговый набор:

Тут, мы сначала указываем индексы нашим наборам, затем объединяем их и сбрасываем индексы итогового набора. Подробнее о этих операция можно прочитать в одной из моих прошлых статей. Осталось выгрузить полученный dataframe в текстовый файл, для сохранности:

Обработчик события одного события UFC

Страницу с перечнем турниров мы выгрузили в удобном формате. Пришло время разобраться со страницами с результатами по соревнований. Для примера возьмем последний турнир и посмотрим HTML код страницы.
Можно заметить, что нужная нам информация содержится в элементе с классом data_table row_is_link. В целом процесс парсинга похож на показанный выше, за одним исключением: таблица результатов оформлена не совсем корректно.
Некорретность ее в том, что для каждого бойца в ней заведена отдельная строка, что никак не удобно при анализе. Чтобы избавиться от этого неудобства при разборе результатов я принял решение использовать итератор, только по нечетным строкам. Номер же четной вычислять из текущей нечетной строки.
Таким образом я буду обрабатывать сразу пару строк и переносить их в строку. Код будет следующий:

Можно заметить, что для каждого поединка дополнительно записывается название турнира. Это нужно для того, чтобы определить дату поединка.
Сохраним теперь полученные результаты в файл:

Парсинг XML Python

Xml парсинг

Вы когда-нибудь сталкивались с надоедливым XML-файлом, который вам нужно проанализировать, чтобы получить важные значения? Давайте узнаем, как создать парсер Python XML.

Мы рассмотрим, как мы можем анализировать подобные XML-файлы с помощью Python, чтобы получить соответствующие атрибуты и значения.

Метод 1: Использование ElementTree (рекомендуется)

Мы можем использовать библиотеку ElementTree Python для решения этой задачи.

Это самый простой и рекомендуемый вариант для создания синтаксического анализатора Python XML, поскольку эта библиотека по умолчанию входит в состав Python.

Она не только обеспечивает легкий доступ, поскольку уже установлена, но и работает довольно быстро. Давайте посмотрим, как именно мы можем извлечь атрибуты из нашего тестового файла.

Мы будем использовать интерфейс xml.etree.ElementTree внутри основного xml пакета.

Дерево синтаксического анализатора

Давайте сначала построим корневой узел этого дерева синтаксического анализа. Это самый верхний узел, он необходим нам для начала синтаксического анализа.

К счастью для нас, в этом API уже есть следующий метод:

Это автоматически прочитает входной XML-файл и получит для нас корневой узел.

Похоже, он проанализирован. Но мы пока не можем это проверить. Итак, давайте проанализируем другие атрибуты и попробуем получить значение.

Получение значения соответствующих атрибутов

Итак, теперь наша задача — получить значение внутри атрибута <heading> с помощью нашего Python XML Parser.

Его позиция от корневого узла <page> — <header/type> , поэтому нам нужно перебрать все совпадения на этом уровне дерева.

Мы можем сделать это с помощью root_node.findall(level) , где level — это желаемая позиция (в нашем случае <header/type> ).

tag.get(attribute) получит значение нашего <attribute> на уровнях, на которых мы ищем. Итак, нам просто нужно сделать это в <header/type> и получить значения атрибутов <heading> и <text> . Это оно!

Мы получили все значения на этом уровне нашего дерева синтаксического анализа XML! Мы успешно проанализировали наш XML-файл.

Возьмем другой пример, чтобы все прояснить.

Теперь предположим, что XML-файл выглядит так:

Здесь мы должны не только получить значения атрибутов name , но также получить текстовые значения 10, 20, 30 и 40 для каждого элемента на этом уровне.

Чтобы получить значение атрибута name , мы можем сделать то же самое, что и раньше. Мы также можем использовать tag.attrib[name] чтобы получить значение. Это то же самое, что и tag.get(name) , за исключением того, что он использует поиск по словарю.

Получить текстовое значение просто. Просто используйте:

Итак, наша полная программа для этого парсера будет:

Вы можете расширить эту логику на любое количество уровней и для файлов XML произвольной длины! Вы также можете записать новое дерево синтаксического анализа в другой файл XML.

Метод 2: использование BeautifulSoup (надежный)

Это также еще один хороший выбор, если по какой-то причине исходный XML плохо отформатирован. XML может работать не очень хорошо, если вы не выполните предварительную обработку файла.

Оказывается, BeautifulSoup очень хорошо работает со всеми этими типами файлов, поэтому, если вы хотите проанализировать любой XML-файл, используйте этот подход.

Чтобы установить его, используйте pip и установите модуль bs4 :

Я дам вам небольшой фрагмент нашего предыдущего XML-файла:

Я передам этот файл, а затем bs4 его с помощью bs4 .

Синтаксис аналогичен нашему модулю xml , поэтому мы по-прежнему получаем имена атрибутов, используя value = tag[‘attribute_name’] и text = tag.text . Точно так же, как и раньше!

Мы также проанализировали это с помощью bs4 ! Если ваш исходный XML файл плохо отформатирован, можно использовать этот метод, поскольку BeautifulSoup имеет другие правила для обработки таких файлов.

Parsing XML and HTML with lxml

lxml provides a very simple and powerful API for parsing XML and HTML. It supports one-step parsing as well as step-by-step parsing using an event-driven API (currently only for XML).

The usual setup procedure:

The following examples also use StringIO or BytesIO to show how to parse from files and file-like objects. Both are available in the io module:

Parsers

Parsers are represented by parser objects. There is support for parsing both XML and (broken) HTML. Note that XHTML is best parsed as XML, parsing it with the HTML parser can lead to unexpected results. Here is a simple example for parsing XML from an in-memory string:

To read from a file or file-like object, you can use the parse() function, which returns an ElementTree object:

Note how the parse() function reads from a file-like object here. If parsing is done from a real file, it is more common (and also somewhat more efficient) to pass a filename:

lxml can parse from a local file, an HTTP URL or an FTP URL. It also auto-detects and reads gzip-compressed XML files (.gz).

If you want to parse from memory and still provide a base URL for the document (e.g. to support relative paths in an XInclude), you can pass the base_url keyword argument:

Parser options

The parsers accept a number of setup options as keyword arguments. The above example is easily extended to clean up namespaces during parsing:

The keyword arguments in the constructor are mainly based on the libxml2 parser configuration. A DTD will also be loaded if validation or attribute default values are requested.

Available boolean keyword arguments:

  • attribute_defaults — read the DTD (if referenced by the document) and add the default attributes from it
  • dtd_validation — validate while parsing (if a DTD was referenced)
  • load_dtd — load and parse the DTD while parsing (no validation is performed)
  • no_network — prevent network access when looking up external documents (on by default)
  • ns_clean — try to clean up redundant namespace declarations
  • recover — try hard to parse through broken XML
  • remove_blank_text — discard blank text nodes between tags, also known as ignorable whitespace. This is best used together with a DTD or schema (which tells data and noise apart), otherwise a heuristic will be applied.
  • remove_comments — discard comments
  • remove_pis — discard processing instructions
  • strip_cdata — replace CDATA sections by normal text content (on by default)
  • resolve_entities — replace entities by their text value (on by default)
  • huge_tree — disable security restrictions and support very deep trees and very long text content (only affects libxml2 2.7+)
  • compact — use compact storage for short text content (on by default)
  • collect_ids — collect XML IDs in a hash table while parsing (on by default). Disabling this can substantially speed up parsing of documents with many different IDs if the hash lookup is not used afterwards.

Other keyword arguments:

  • encoding — override the document encoding
  • target — a parser target object that will receive the parse events (see The target parser interface)
  • schema — an XMLSchema to validate against (see validation)

Error log

Parsers have an error_log property that lists the errors and warnings of the last parser run:

Each entry in the log has the following properties:

  • message: the message text
  • domain: the domain ID (see the lxml.etree.ErrorDomains class)
  • type: the message type ID (see the lxml.etree.ErrorTypes class)
  • level: the log level ID (see the lxml.etree.ErrorLevels class)
  • line: the line at which the message originated (if applicable)
  • column: the character column at which the message originated (if applicable)
  • filename: the name of the file in which the message originated (if applicable)

For convenience, there are also three properties that provide readable names for the ID values:

  • domain_name
  • type_name
  • level_name

To filter for a specific kind of message, use the different filter_*() methods on the error log (see the lxml.etree._ListErrorLog class).

Parsing HTML

HTML parsing is similarly simple. The parsers have a recover keyword argument that the HTMLParser sets by default. It lets libxml2 try its best to return a valid HTML tree with all content it can manage to parse. It will not raise an exception on parser errors. You should use libxml2 version 2.6.21 or newer to take advantage of this feature.

Lxml has an HTML function, similar to the XML shortcut known from ElementTree:

The support for parsing broken HTML depends entirely on libxml2’s recovery algorithm. It is not the fault of lxml if you find documents that are so heavily broken that the parser cannot handle them. There is also no guarantee that the resulting tree will contain all data from the original document. The parser may have to drop seriously broken parts when struggling to keep parsing. Especially misplaced meta tags can suffer from this, which may lead to encoding problems.

Note that the result is a valid HTML tree, but it may not be a well-formed XML tree. For example, XML forbids double hyphens in comments, which the HTML parser will happily accept in recovery mode. Therefore, if your goal is to serialise an HTML document as an XML/XHTML document after parsing, you may have to apply some manual preprocessing first.

Also note that the HTML parser is meant to parse HTML documents. For XHTML documents, use the XML parser, which is namespace aware.

Doctype information

The use of the libxml2 parsers makes some additional information available at the API level. Currently, ElementTree objects can access the DOCTYPE information provided by a parsed document, as well as the XML version and the original encoding. Since lxml 3.5, the doctype references are mutable.

The target parser interface

As in ElementTree, and similar to a SAX event handler, you can pass a target object to the parser:

It is important for the .close() method to reset the parser target to a usable state, so that you can reuse the parser as often as you like:

Starting with lxml 2.3, the .close() method will also be called in the error case. This diverges from the behaviour of ElementTree, but allows target objects to clean up their state in all situations, so that the parser can reuse them afterwards.

Note that the parser does not build a tree when using a parser target. The result of the parser run is whatever the target object returns from its .close() method. If you want to return an XML tree here, you have to create it programmatically in the target object. An example for a parser target that builds a tree is the TreeBuilder:

The feed parser interface

Since lxml 2.0, the parsers have a feed parser interface that is compatible to the ElementTree parsers. You can use it to feed data into the parser in a controlled step-by-step way.

In lxml.etree, you can use both interfaces to a parser at the same time: the parse() or XML() functions, and the feed parser interface. Both are independent and will not conflict (except if used in conjunction with a parser target object as described above).

To start parsing with a feed parser, just call its feed() method to feed it some data.

When you are done parsing, you must call the close() method to retrieve the root Element of the parse result document, and to unlock the parser:

If you do not call close(), the parser will stay locked and subsequent feeds will keep appending data, usually resulting in a non well-formed document and an unexpected parser error. So make sure you always close the parser after use, also in the exception case.

Another way of achieving the same step-by-step parsing is by writing your own file-like object that returns a chunk of data on each read() call. Where the feed parser interface allows you to actively pass data chunks into the parser, a file-like object passively responds to read() requests of the parser itself. Depending on the data source, either way may be more natural.

Note that the feed parser has its own error log called feed_error_log. Errors in the feed parser do not show up in the normal error_log and vice versa.

You can also combine the feed parser interface with the target parser:

Again, this prevents the automatic creation of an XML tree and leaves all the event handling to the target object. The close() method of the parser forwards the return value of the target’s close() method.

Incremental event parsing

In Python 3.4, the xml.etree.ElementTree package gained an extension to the feed parser interface that is implemented by the XMLPullParser class. It additionally allows processing parse events after each incremental parsing step, by calling the .read_events() method and iterating over the result. This is most useful for non-blocking execution environments where data chunks arrive one after the other and should be processed as far as possible in each step.

The same feature is available in lxml 3.3. The basic usage is as follows:

Just like the normal feed parser, the XMLPullParser builds a tree in memory (and you should always call the .close() method when done with parsing):

However, since the parser provides incremental access to that tree, you can explicitly delete content that you no longer need once you have processed it. Read the section on Modifying the tree below to see what you can do here and what kind of modifications you should avoid.

In lxml, it is enough to call the .read_events() method once as the iterator it returns can be reused when new events are available.

Also, as known from other iterators in lxml, you can pass a tag argument that selects which parse events are returned by the .read_events() iterator.

Event types

The parse events are tuples (event-type, object). The event types supported by ElementTree and lxml.etree are the strings ‘start’, ‘end’, ‘start-ns’ and ‘end-ns’. The ‘start’ and ‘end’ events represent opening and closing elements. They are accompanied by the respective Element instance. By default, only ‘end’ events are generated, whereas the example above requested the generation of both ‘start’ and ‘end’ events.

The ‘start-ns’ and ‘end-ns’ events notify about namespace declarations. They do not come with Elements. Instead, the value of the ‘start-ns’ event is a tuple (prefix, namespaceURI) that designates the beginning of a prefix-namespace mapping. The corresponding end-ns event does not have a value (None). It is common practice to use a list as namespace stack and pop the last entry on the ‘end-ns’ event.

Modifying the tree

You can modify the element and its descendants when handling the ‘end’ event. To save memory, for example, you can remove subtrees that are no longer needed:

WARNING: During the ‘start’ event, any content of the element, such as the descendants, following siblings or text, is not yet available and should not be accessed. Only attributes are guaranteed to be set. During the ‘end’ event, the element and its descendants can be freely modified, but its following siblings should not be accessed. During either of the two events, you must not modify or move the ancestors (parents) of the current element. You should also avoid moving or discarding the element itself. The golden rule is: do not touch anything that will have to be touched again by the parser later on.

If you have elements with a long list of children in your XML file and want to save more memory during parsing, you can clean up the preceding siblings of the current element:

The while loop deletes multiple siblings in a row. This is only necessary if you skipped over some of them using the tag keyword argument. Otherwise, a simple if should do. The more selective your tag is, however, the more thought you will have to put into finding the right way to clean up the elements that were skipped. Therefore, it is sometimes easier to traverse all elements and do the tag selection by hand in the event handler code.

Selective tag events

As an extension over ElementTree, lxml.etree accepts a tag keyword argument just like element.iter(tag). This restricts events to a specific tag or namespace:

Comments and PIs

As an extension over ElementTree, the XMLPullParser in lxml.etree also supports the event types ‘comment’ and ‘pi’ for the respective XML structures.

Events with custom targets

You can combine the pull parser with a parser target. In that case, it is the target’s responsibility to generate event values. Whatever it returns from its .start() and .end() methods will be returned by the pull parser as the second item of the parse events tuple.

As you can see, the event values do not even have to be Element objects. The target is generally free to decide how it wants to create an XML tree or whatever else it wants to make of the parser callbacks. In many cases, however, you will want to make your custom target inherit from the TreeBuilder class in order to have it build a tree that you can process normally. The start() and .end() methods of TreeBuilder return the Element object that was created, so you can override them and modify the input or output according to your needs. Here is an example that filters attributes before they are being added to the tree:

iterparse and iterwalk

As known from ElementTree, the iterparse() utility function returns an iterator that generates parser events for an XML file (or file-like object), while building the tree. You can think of it as a blocking wrapper around the XMLPullParser that automatically and incrementally reads data from the input file for you and provides a single iterator for them:

After parsing, the resulting tree is available through the root property of the iterator:

The other event types can be activated with the events keyword argument:

iterparse() also supports the tag argument for selective event iteration and several other parameters that control the parser setup. The tag argument can be a single tag or a sequence of tags. You can also use it to parse HTML input by passing html=True.

iterwalk

For convenience, lxml also provides an iterwalk() function. It behaves exactly like iterparse(), but works on Elements and ElementTrees. Here is an example for a tree parsed by iterparse():

And now we can take the resulting in-memory tree and iterate over it using iterwalk() to get the exact same events without parsing the input again:

In order to avoid wasting time on uninteresting parts of the tree, the iterwalk iterator can be instructed to skip over an entire subtree with its .skip_subtree() method.

Note that .skip_subtree() only has an effect when handling start or start-ns events.

Python unicode strings

lxml.etree has broader support for Python unicode strings than the ElementTree library. First of all, where ElementTree would raise an exception, the parsers in lxml.etree can handle unicode strings straight away. This is most helpful for XML snippets embedded in source code using the XML() function:

This requires, however, that unicode strings do not specify a conflicting encoding themselves and thus lie about their real encoding:

Similarly, you will get errors when you try the same with HTML data in a unicode string that specifies a charset in a meta tag of the header. You should generally avoid converting XML/HTML data to unicode before passing it into the parsers. It is both slower and error prone.

Serialising to Unicode strings

To serialize the result, you would normally use the tostring() module function, which serializes to plain ASCII by default or a number of other byte encodings if asked for:

As an extension, lxml.etree recognises the name ‘unicode’ as an argument to the encoding parameter to build a Python unicode representation of a tree:

The result of tostring(encoding='unicode') can be treated like any other Python unicode string and then passed back into the parsers. However, if you want to save the result to a file or pass it over the network, you should use write() or tostring() with a byte encoding (typically UTF-8) to serialize the XML. The main reason is that unicode strings returned by tostring(encoding='unicode') are not byte streams and they never have an XML declaration to specify their encoding. These strings are most likely not parsable by other XML libraries.

For normal byte encodings, the tostring() function automatically adds a declaration as needed that reflects the encoding of the returned string. This makes it possible for other parsers to correctly parse the XML byte stream. Note that using tostring() with UTF-8 is also considerably faster in most cases.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *