- Class Selector
- Combinators
- Pseudo selectors
- Structural pseudo selectors
- Use selector-syntax to find elements
- Solution
- Description
- Selector overview
- Selector combinations
- Pseudo selectors
- Cookbook contents
- Introduction
- Лёгкий парсинг HTML с помощью jsoup
- Быстрый старт
- Использование
- Заключение
- Spring MVC: обработка формы, вып.
- Spring MVC выберите тег
Class Selector
A selector is a chain of simple selectors, separated by combinators. Selectors are case insensitive (including against elements, attributes, and attribute values).
The universal selector (*) is implicit when no element selector is supplied (i.e. *.header and .header is equivalent).
Combinators
Pseudo selectors
div:not(:has(div)) finds divs that do not contain divs.
To find content that includes parentheses, escape those with a \ .
p:contains(hello \(there\) finds p elements containing the text «Hello (There)»
To find content that includes parentheses, escape those with a \ .
To find content that includes parentheses, escape those with a \ .
Note that using this selector will modify the DOM, so you may want to clone your document before using.
Structural pseudo selectors
elements that have an+b-1 siblings before it in the document tree, for any positive integer or zero value of n , and has a parent element. For values of a and b greater than zero, this effectively divides the element’s children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.
A word on using regular expressions in these selectors: depending on the content of the regex, you will need to quote the pattern using Pattern.quote(«regex») for it to parse correctly through both the selector parser and the regex parser. E.g. String query = «div:matches(» + Pattern.quote(regex) + «);» .
Escaping special characters: to match a tag, ID, or other selector that does not follow the regular CSS syntax, the query must be escaped with the \ character. For example, to match by ID
, use document.select(«#i\\.d») .
Use selector-syntax to find elements
You want to find or manipulate elements using a CSS or jquery-like selector syntax.
Solution
File input = new File("/tmp/input.html"); Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/"); Elements links = doc.select("a[href]"); // a with href Elements pngs = doc.select("img[src$=.png]"); // img with src ending .png Element masthead = doc.select("div.masthead").first(); // div with resultLinks = doc.select("h3.r > a"); // direct a after h3
Description
jsoup elements support a CSS (or jquery) like selector syntax to find matching elements, that allows very powerful and robust queries.
The select method is available in a Document , Element , or in Elements . It is contextual, so you can filter by selecting from a specific element, or by chaining select calls.
Select returns a list of Elements (as Elements ), which provides a range of methods to extract and manipulate the results.
Selector overview
- tagname : find elements by tag, e.g. a
- ns|tag : find elements by tag in a namespace, e.g. fb|name finds elements
- #id : find elements by ID, e.g. #logo
- .class : find elements by class name, e.g. .masthead
- [attribute] : elements with attribute, e.g. [href]
- [^attr] : elements with an attribute name prefix, e.g. [^data-] finds elements with HTML5 dataset attributes
- [attr=value] : elements with attribute value, e.g. [width=500] (also quotable, like [data-name=’launch sequence’] )
- [attr^=value] , [attr$=value] , [attr*=value] : elements with attributes that start with, end with, or contain the value, e.g. [href*=/path/]
- [attr~=regex] : elements with attribute values that match the regular expression; e.g. img[src~=(?i)\.(png|jpe?g)]
- * : all elements, e.g. *
Selector combinations
- el#id : elements with ID, e.g. div#logo
- el.class : elements with class, e.g. div.masthead
- el[attr] : elements with attribute, e.g. a[href]
- Any combination, e.g. a[href].highlight
- ancestor child : child elements that descend from ancestor, e.g. .body p finds p elements anywhere under a block with class «body»
- parent > child : child elements that descend directly from parent, e.g. div.content > p finds p elements; and body > * finds the direct children of the body tag
- siblingA + siblingB : finds sibling B element immediately preceded by sibling A, e.g. div.head + div
- siblingA ~ siblingX : finds sibling X element preceded by sibling A, e.g. h1 ~ p
- el, el, el : group multiple selectors, find unique elements that match any of the selectors; e.g. div.masthead, div.logo
Pseudo selectors
- :lt(n) : find elements whose sibling index (i.e. its position in the DOM tree relative to its parent) is less than n ; e.g. td:lt(3)
- :gt(n) : find elements whose sibling index is greater than n ; e.g. div p:gt(2)
- :eq(n) : find elements whose sibling index is equal to n ; e.g. form input:eq(1)
- :has(selector) : find elements that contain elements matching the selector; e.g. div:has(p)
- :not(selector) : find elements that do not match the selector; e.g. div:not(.logo)
- :contains(text) : find elements that contain the given text. The search is case-insensitive; e.g. p:contains(jsoup)
- :containsOwn(text) : find elements that directly contain the given text
- :matches(regex) : find elements whose text matches the specified regular expression; e.g. div:matches((?i)login)
- :matchesOwn(regex) : find elements whose own text matches the specified regular expression
- Note that the above indexed pseudo-selectors are 0-based, that is, the first element is at index 0, the second at 1, etc
See the Selector API reference for the full supported list and details.
Cookbook contents
Introduction
Лёгкий парсинг HTML с помощью jsoup
Возможно, когда-нибудь вам будет необходимо получить информацию с какого-либо сайта либо HTML-документа в своем приложении, и я без лишних слов скажу, что использование библиотеки jsoup существенно упростит вашу задачу. Как говорится на wiki, jsoup — это Java-библиотека с открытым исходным кодом, предназначенная для анализа, извлечения и управления данными, хранящимися в документах HTML.
Быстрый старт
Библиотеку можно скачать в виде jar файла и поместить в проект, а также подключить с помощью Maven/Gradle. Ссылку на официальный сайт я оставлю в конце статьи: там вы сможете найти актуальную версию библиотеки. В примере будем использовать подключение через Maven. Добавим зависимость:
Использование
Первым делом вам необходимо получить экземпляр класса Document из org.jsoup.nodes.Document с указанием на источник для разбора. Им может выступать как локальный файл, так и ссылка. Для примера, в данной статье мы будем использовать сайт yandex.ru и попытаемся получить их актуальную новостную ленту:
Document doc = Jsoup.connect("https://yandex.ru/") .userAgent("Chrome/4.0.249.0 Safari/532.5") .referrer("http://www.google.com") .get();
User Agent является идентификатором, который сообщается посещаемому сайту. На многих сайтах он является важнейшим критерием для антиспам фильтра. Referrer содержит URL источника запроса. Метод get() вызывает обрабатываемое исключение IOException, так что мы можем обернуть все в try/catch блок, либо просто перебросить его дальше с помощью throws . На данный момент мы получили исходный код данной страницы. При необходимости библиотека jsoup сама может восстановить поврежденные элементы. Теперь нам остается лишь сузить поиск до отдельного блока. Метод select() имеет большую выборку в использовании: он позволяет искать элементы по тегу, атрибутам, классу и другим параметрам. Почти все современные браузеры поддерживают возможность быстрого поиска исходного кода выбранного элемента. Нехитрыми манипуляциями, мы находим исходный код нужного нам элемента и получаем div блок с указанным классом, его мы и будем использовать для выборки. Воспользуемся классом Elements из org.jsoup.select.Elements, для выборки всех элементов из нашего выбранного блока.
Elements listNews = doc.select("div#tabnews_newsc.content-tabs__items.content-tabs__items_active_true");
Сейчас мы имеем что то вроде этого: Теперь нам остается лишь использовать небольшой цикл для пробора всех элементов:
for (Element element : listNews.select("a")) System.out.println(element.text());
Метод text() позволяет отбросить код разметки и оставляет лишь сочетание текста для всех входящих элементов. Результат выполнения будет таков: Нетрудно заметить, что реальное количество полученных строк не соответствует фактическому отображению на странице. В этом и заключаются подводные камни. Если посмотреть исходный код разметки, можно заметить, что последняя новость анимационно меняется с определенным интервалом времени. Часть таких «камней» решается дополнительной выборкой, ну и конечно тестами. Может оказаться так, что первые пять элементов будут содержать нужную нам информацию, а на шестом элементе будет лишь заскриптованная пустая строка. Бывает и такое, что блоки не будут обладать какими-либо идентификаторами, тогда есть возможностью прямо указать с помощью метода get(int index) на номер позиции рассматриваемого элемента.
System.out.println(listNews.select("a").get(2).text());
Заключение
В данном примере показана лишь малая часть того, на что способен jsoup. Не стоит отменять и тот факт, что сайты нередко обновляются, изменяя структуру кода разметки, так что при работе с парсингом нужно быть готовым адаптироваться к изменениям. Больше информации и актуальную версию вы можете получить на официальном сайте jsoup.org, более подробно почитать про классы и методы можно по ссылке o7planning.org. Оставлю ссылку на мой github, на момент написания статьи там находится несколько Telegram-ботов, которые используют Jsoup для получения и выдачи информации.
Spring MVC: обработка формы, вып.
Выпадающие списки являются одним из наиболее частых элементов в веб-формах. В HTML вы можете создать такой элемент управления, используя соответствующие теги: — родительский тег раскрывающегося списка и — дочерний тег тега . Библиотека тегов Spring MVC имеет собственное решение для выпадающих списков. В этом посте я напишу о тегах , и .
В предыдущих статьях об обработке форм с использованием Spring MVC я сделал обзор случаев, когда нам нужно связать текстовое поле, флажки или переключатели с помощью объекта Java. Почти все шаги будут повторяться для элемента выбора выпадающего списка . Далее я рассмотрю три ситуации с выпадающими списками в контексте связывания его с Java-объектом с использованием библиотеки тегов Spring MVC. Первый случай будет о форме: выберите тег со значениями, основанными на java.util.Map , второй пример будет об использовании формы: выберите тег в сочетании с тегами формы: опции , третий пример будет об использовании формы: выберите тег в сочетании с формой: параметры тега.
Каждый пример будет иметь одинаковый результат jsp-страницы, поэтому будут отличаться только страницы формы и контроллеры для них. Настройка конфигурации будет опущена, потому что это было объяснено в одной из предыдущих статей .
Spring MVC выберите тег
Предположим, что пользователь веб-приложения может выбрать производителя мобильного телефона (например, HTC, SAMSUNG, IPHONE и т. Д.). Мы можем реализовать это несколькими способами, используя библиотеку тегов Spring MVC.
Модель предметной области: