Test

Чтение веб-страницы с помощью Python

Доброго времени суток! Для начала у меня появился вот такой вопросик. Можно ли считать программную обработку содержимого html старничек веб-программированием? Вроде в вебе работаем, имеем дело с сетевыми протоколами и все такое. Кто точно знает ответ на этот вопрос, поделитесь в комментариях, я буду признателен.

Но перейдем к делу. Недавно в университете нам выдали интересное задание, связанное с чтением веб-страниц с помощью Python на. Научитесь, говорят, считывать страницы. Насколько я знаю, это весьма нетривиальная задача для решения на C/C++. Но чего только нет в стандартной библиотеке Python. Оказывается, существует специальный модуль urllib для работы с урлами. Замечательно! Даже искать не пришлось. Пара слов о том, какие функции мне понадобились из этого модуля.

Как прочитать веб-страницу с помощью Python

Будем пользоваться модулем под названием request , который входит в состав упомянутого выше urllib . И более того, используем всего лишь одну единственную и жутко простую функцию urlopen . Из названия нетрудно догадаться, чем она занимается.

В случае, когда схема ulr а имеет тип file(например урлы файлов в локальной сети), создастся идентификатор этого файла, как при обычном вызове open. Если же ссылка ведет в сеть, страничка будет загружена, считана и нам вернется файло-подобный индентификатор, для которого доступны все любимые нами методы. Такие, как read(), readlines(), close(), info() и некоторые другие.

Питон тем и крут, что можно особо не заморачиваться над тем, как это работает и читать ссылку, как обычный файл. Отличие только в том, что html страница всегда читается в виде массива байт. Это значит, что для удобства обработки, строки нужно декодировать в utf-8 с помощью метода decode(‘utf-8’) .

Читайте также:  Javascript переменная get запроса

Пример использования

Задача состоит в том, чтобы вытащить с сайта математического факультета список всех сотрудников и их контактные данные. Поиграем немного в шпионов? Шутка, данные ведь общедоступные. Да и реализация мягко говоря не тянет на секретный алгоритм слежки. Потому что я писал конкретно разбор этого сайта, учитывая структуру его html документов.

Исходный код решения

Заключение

Тут и добавить особо нечего, читать ссылки, как обычные файлы это очень круто. Можно научиться поднимать свой локальный сервер и делать из него агрегатор статей с новостных сайтов. А можно раскачаться окончательно и написать свой аналог google translate. Но это оставим на потом, спасибо за внимание!

Источник

html.parser — Simple HTML and XHTML parser¶

This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.

class html.parser. HTMLParser ( * , convert_charrefs = True ) ¶

Create a parser instance able to parse invalid markup.

If convert_charrefs is True (the default), all character references (except the ones in script / style elements) are automatically converted to the corresponding Unicode characters.

An HTMLParser instance is fed HTML data and calls handler methods when start tags, end tags, text, comments, and other markup elements are encountered. The user should subclass HTMLParser and override its methods to implement the desired behavior.

This parser does not check that end tags match start tags or call the end-tag handler for elements which are closed implicitly by closing an outer element.

Changed in version 3.4: convert_charrefs keyword argument added.

Changed in version 3.5: The default value for argument convert_charrefs is now True .

Example HTML Parser Application¶

As a basic example, below is a simple HTML parser that uses the HTMLParser class to print out start tags, end tags, and data as they are encountered:

from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Encountered a start tag:", tag) def handle_endtag(self, tag): print("Encountered an end tag :", tag) def handle_data(self, data): print("Encountered some data :", data) parser = MyHTMLParser() parser.feed('' '

Parse me!

'
)
Encountered a start tag: html Encountered a start tag: head Encountered a start tag: title Encountered some data : Test Encountered an end tag : title Encountered an end tag : head Encountered a start tag: body Encountered a start tag: h1 Encountered some data : Parse me! Encountered an end tag : h1 Encountered an end tag : body Encountered an end tag : html

HTMLParser Methods¶

HTMLParser instances have the following methods:

Feed some text to the parser. It is processed insofar as it consists of complete elements; incomplete data is buffered until more data is fed or close() is called. data must be str .

Force processing of all buffered data as if it were followed by an end-of-file mark. This method may be redefined by a derived class to define additional processing at the end of the input, but the redefined version should always call the HTMLParser base class method close() .

Reset the instance. Loses all unprocessed data. This is called implicitly at instantiation time.

Return current line number and offset.

Return the text of the most recently opened start tag. This should not normally be needed for structured processing, but may be useful in dealing with HTML “as deployed” or for re-generating input with minimal changes (whitespace between attributes can be preserved, etc.).

The following methods are called when data or markup elements are encountered and they are meant to be overridden in a subclass. The base class implementations do nothing (except for handle_startendtag() ):

HTMLParser. handle_starttag ( tag , attrs ) ¶

This method is called to handle the start tag of an element (e.g. ).

The tag argument is the name of the tag converted to lower case. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. The name will be translated to lower case, and quotes in the value have been removed, and character and entity references have been replaced.

For instance, for the tag , this method would be called as handle_starttag(‘a’, [(‘href’, ‘https://www.cwi.nl/’)]) .

All entity references from html.entities are replaced in the attribute values.

HTMLParser. handle_endtag ( tag ) ¶

This method is called to handle the end tag of an element (e.g.

).

The tag argument is the name of the tag converted to lower case.

HTMLParser. handle_startendtag ( tag , attrs ) ¶

Similar to handle_starttag() , but called when the parser encounters an XHTML-style empty tag ( ). This method may be overridden by subclasses which require this particular lexical information; the default implementation simply calls handle_starttag() and handle_endtag() .

HTMLParser. handle_data ( data ) ¶

This method is called to process arbitrary data (e.g. text nodes and the content of and

).

HTMLParser. handle_entityref ( name ) ¶

This method is called to process a named character reference of the form &name; (e.g. > ), where name is a general entity reference (e.g. ‘gt’ ). This method is never called if convert_charrefs is True .

HTMLParser. handle_charref ( name ) ¶

This method is called to process decimal and hexadecimal numeric character references of the form &#NNN; and &#xNNN; . For example, the decimal equivalent for > is > , whereas the hexadecimal is > ; in this case the method will receive ’62’ or ‘x3E’ . This method is never called if convert_charrefs is True .

HTMLParser. handle_comment ( data ) ¶

This method is called when a comment is encountered (e.g. ).

For example, the comment will cause this method to be called with the argument ‘ comment ‘ .

The content of Internet Explorer conditional comments (condcoms) will also be sent to this method, so, for

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