Парсинг 2 таблиц с одинаковым классом diva
Eсть div entry класса updatetablebody.
В него вложено 2 id которые называются version и description.
Ниже на странице есть так же div entry с классом updatetablebody
Но в него вложено 2 id которые называются patch и description.
Мне нужно распарсить эту страницу таким образом, чтобы первый div entry с его id парсились отдельно от второго diva entry.
public static void SomeMethod() throws IOException{
Document doc = Jsoup.connect(URL).get();
Elements entries = doc.select(".updatetablebody #entry");
System.out.println("Somthing: ");
for (Element entry : entries) {
if (entry.hasAttr("div.patch")) {
Element patch = entry.selectFirst("#patch");
assert patch != null;
String patchText = patch.text();
Element descriptionPatch = entry.selectFirst("#description");
assert descriptionPatch != null;
String descriptionPatchText = descriptionPatch.text();
System.out.println("Patch: " + patchText);
System.out.println("Description: " + descriptionPatchText);
}
else {
Element version = entry.selectFirst("#version");
assert version != null;
String versionText = version.text();
Element description = entry.selectFirst("#description");
assert description != null;
String descriptionText = description.text();
System.out.println("Version: " + versionText);
System.out.println("Description: " + descriptionText);
}
}
}
<div class = "updatetablebody">
<div id="entry">
<div id="version"><a href="/ru/wiki/%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F_7.32c" title="Версия 7.32c">7.32c</a></div>
<div id="description"><span id="7.32c"></span>
<ul><li><span class="image-link"><a href="/ru/wiki/Phantom_Lancer" title="Phantom Lancer"><img alt="Spirit Lance icon" src="https://static.wikia.nocookie.net/dota2_gamepedia/images/f/fd/Spirit_Lance_icon.png/revision/latest/scale-to-width-down/18?cb=20120425195445" decoding="async" loading="lazy" width="18" height="18" class="noprint" data-image-name="Spirit Lance icon.png" data-image-key="Spirit_Lance_icon.png" data-relevant="0"></a> <a href="/ru/wiki/Phantom_Lancer#Spirit_Lance" title="Phantom Lancer">Spirit Lance</a></span>
<ul><li>Дальность применения увеличена с 525/600/675/750 до 600/650/700/750.</li>
<li>Замедление <a href="/ru/wiki/%D0%A1%D0%BA%D0%BE%D1%80%D0%BE%D1%81%D1%82%D1%8C_%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%D0%B2%D0%B8%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F" title="Скорость передвижения">скорости передвижения</a> увеличено с 10%/18%/26%/34% до 14%/21%/28%/35%.</li></ul></li></ul></div>
</div>
<div class = "updatetablebody">
<div id="entry">
<div id="patch"><a href="/ru/wiki/%D0%9E%D0%B1%D0%BD%D0%BE%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_%D0%BE%D1%82_4_%D0%BD%D0%BE%D1%8F%D0%B1%D1%80%D1%8F_2021" title="Обновление от 4 ноября 2021">4 ноября 2021</a></div>
<div id="description"><span id="2021-11-04"></span>
<ul><li>Updated <span class="image-link"><a href="/ru/wiki/Phantom_Lancer" title="Phantom Lancer"><img alt="Doppelganger icon" src="https://static.wikia.nocookie.net/dota2_gamepedia/images/e/e2/Doppelganger_icon.png/revision/latest/scale-to-width-down/18?cb=20140924015254" decoding="async" loading="lazy" width="18" height="18" class="noprint ls-is-cached lazyloaded" data-image-name="Doppelganger icon.png" data-image-key="Doppelganger_icon.png" data-relevant="0" data-src="https://static.wikia.nocookie.net/dota2_gamepedia/images/e/e2/Doppelganger_icon.png/revision/latest/scale-to-width-down/18?cb=20140924015254"></a> <a href="/ru/wiki/Phantom_Lancer#Doppelganger" title="Phantom Lancer">Doppelganger</a></span> ability tooltip.</li></ul></div>
</div>
У меня получается что-то вроде такого, но это не работает и парсит только div где id version и description. И, получается, позже возникает проблема с NullPointerException. Так как description еще есть и он его видит, а вот version закончились. Помогите, кто чем сможет)
Ответы (1 шт):
Исправил такой вопрос следующим путем.
public static void someMethod() throws IOException {
Document doc = Jsoup.connect(URLLogs).get();
Element updatetablebodyElements = doc.selectFirst(".updatetablebody");
if (updatetablebodyElements != null) {
Elements entries = updatetablebodyElements.select("#entry");
for (Element entry : entries) {
Element version = entry.selectFirst("#version");
String versionText = version.text();
Element description = entry.selectFirst("#description");
String descriptionText = description.text();
System.out.println("Version: " + versionText);
System.out.println("Description: " + descriptionText);
}
}
}
Селектором нашел первый div с таким классом. Распарсил его и получил нужные мне данные.
Если вдруг кто-то окажется в такой же ситуации - можно найти любую другую таблицу на странице если тот, кто писал HTML-разметку указал одинаковый класс какого-либа дива
public static void SomeMethodButSecondTable() throws IOException {
Document doc = Jsoup.connect(URLLogs).get();
Elements updatetablebodyElements = doc.select(".updatetablebody");
if (updatetablebodyElements.size() >= 2) {
Element secondUpdatetablebody = updatetablebodyElements.get(1);
Elements entries = secondUpdatetablebody.select("#entry");
for (Element entry : entries) {
Element patch = entry.selectFirst("#patch");
String patchText = patch.text();
Element description = entry.selectFirst("#description");
String descriptionText = description.text();
System.out.println("Patch: " + patchText);
System.out.println("Description: " + descriptionText.replaceAll("Н\\s", ""));
}
}
}
if (updatetablebodyElements.size() >= 2) // проверка действительно ли таких "элементов" несколько.
Element secondUpdatetablebody = updatetablebodyElements.get(1); // если несколько - .get(index) выбирает нужный div на всей странице.