2013-11-13 5 views
1

Я пытаюсь использовать JSoup для получения некоторого контента с http://dictionary.reference.com/browse/quick. Если вы перейдете на эту страницу, вы увидите, что способ организации данных состоит в том, чтобы представить каждый «тип слова» (прилагательное, глагол, существительное) для слова быстро как свой раздел, и каждый раздел содержит 1+ списки определений.Использование JSoup для агрегирования данных

Чтобы сделать вещи немного более затруднит, каждое слово в каждом определении есть ссылка на еще одну dictionary.com страница:

quick 
    adjective 
     1. done, proceeding, or occurring with promptness or rapidity... 
     2. that is over or completed within a short interval of time 
     ... 
     14. Archaic. 
      a. endowed with life 
      b. having a high degree of vigor, energy, ... 
    noun 
     1. living persons; the quick and the dead 
     2. the tender, sensitive flesh of the living body... 
     ... 
    adverb 
     ... 

То, что я хочу сделать, это использовать JSoup для получения типов слов и их соответствующие определения в виде списка строк, например:

public class Metadata { 
    // Ex: "adjective", "noun", etc. 
    private String wordType; 

    // Ex: String #1: "1. done, proceeding, or occurring with promptness or rapidity..." 
    //  String #2: "that is over or completed within a short interval of time..." 
    private List<String> definitions; 
} 

Таким образом, страница на самом деле состоит из List<Metadata>, где каждый Metadata элемент представляет собой тип слово в паре 1+ определений.

Я был в состоянии найти список типов слов, используя довольно тривиальное API вызова:

// Contains 1 Element for each word type, like "adjective", "noun", etc. 
Document doc = Jsoup.connect("http://dictionary.reference.com/browse/quick").get(); 
Elements wordTypes = doc.select("div.body div.pbk span.pg"); 

Но я борюсь выяснить, что являюсь флористика нужно doc.select(...) я должен сделать, чтобы получить каждый Metadata экземпляр. У кого-нибудь, кто умеет разбираться в CSS-селекторах и умеет с JSoup, есть идеи? Заранее спасибо!

ответ

0

Там вы идете. Кстати, чтобы проверить CSS селекторов вы можете активировать консоль в инструментах разработчика Chrome и тестовых запросов, как это прямо на их сайте: jQuery('div.body div.pbk div.luna-Ent > .dndata')

Document doc = Jsoup.connect("http://dictionary.reference.com/browse/quick").get(); 
Elements wordTypes = doc.select("div.body div.pbk"); 

for (Element wordType : wordTypes) { 
    Elements typeOfSpeech = wordType.select("span.pg"); 

    System.out.println("typeOfSpeech: " + typeOfSpeech.text()); 

    Elements elements = wordType.select("div.luna-Ent > .dndata"); 

    for (int i = 0; i < elements.size(); i++) { 
     Element element = elements.get(i); 
     System.out.println((i + 1) + ". " + element.text()); 
    } 
} 
2

Если вы посмотрите на HTML, который Jsoup получил с этой страницы вы увидите что-то вроде

<div class="body"> 
    <div class="pbk"> 
     <span class="pg">adjective </span> 
     <div class="luna-Ent"> 
     <span class="dnindex">1.</span> 
     <div class="dndata"> 
     done, proceeding, or occurring with promptness or rapidity, as an action, process, etc.; prompt; immediate: 
     <span class="ital-inline">a quick response.</span> 
     </div> 
     </div> 
     <div class="luna-Ent"> 
     <span class="dnindex">2.</span> 
     <div class="dndata"> 
     that is over or completed within a short interval of time: 
     <span class="ital-inline">a quick shower.</span> 
     </div> 
     </div> 
... 
    <div class="pbk"> 
     <span class="pg">adverb </span> 
     <div class="luna-Ent"> 
     <span class="dnindex">19.</span> 
     <div class="dndata"> 
     <a style="font-style:normal; font-weight:normal;" href="/browse/quickly">quickly</a>. 
     </div> 
     </div> 
    </div> 

Таким образом, каждый раздел

adjective 
    1. done, proceeding, or occurring with promptness or rapidity... 
    2. that is over or completed within a short interval of time 
    ... 
    14. Archaic. 
     a. endowed with life 
     b. having a high degree of vigor, energy, ... 
noun 
    1. living persons; the quick and the dead 
    2. the tender, sensitive flesh of the living body... 
    ... 
adverb 
    ... 

внутри <div class="pbk">, который содержит <span class="pg">adjective </span> с именем Sectio n и определения в divs <div class="luna-Ent">. Таким образом, вы можете попробовать сделать что-то вроде

Document doc = Jsoup.connect("http://dictionary.reference.com/browse/quick").get(); 

Elements sections = doc.select("div.body div.pbk"); 
for (Element element : sections) { 
    String elementType = element.getElementsByClass("pg").text(); 
    System.out.println("--------------------"); 
    System.out.println(elementType); 

    for (Element definitions : element.getElementsByClass("luna-Ent")) 
     System.out.println(definitions.text()); 

} 

Этот код будет выбрать все разделы и найти название раздела с использованием element.getElementsByClass("pg") и определений, используя тот факт, что они находятся в DIV, который имеет класс luna-Entelement.getElementsByClass("luna-Ent") (если вы хотите, чтобы пропустить номера 1., 2. вы можете выбрать dndata класс вместо luna-Ent)

Выход:

-------------------- 
adjective 
1. done, proceeding, or occurring with promptness or rapidity, as an action, process, etc.; prompt; immediate: a quick response. 
2. that is over or completed within a short interval of time: a quick shower. 
3. moving, or able to move, with speed: a quick fox; a quick train. 
4. swift or rapid, as motion: a quick flick of the wrist. 
5. easily provoked or excited; hasty: a quick temper. 
6. keenly responsive; lively; acute: a quick wit. 
7. acting with swiftness or rapidity: a quick worker. 
8. prompt or swift to do something: quick to respond. 
9. prompt to perceive; sensitive: a quick eye. 
10. prompt to understand, learn, etc.; of ready intelligence: a quick student. 
11. (of a bend or curve) sharp: a quick bend in the road. 
12. consisting of living plants: a quick pot of flowers. 
13. brisk, as fire, flames, heat, etc. 
14. Archaic. a. endowed with life. b. having a high degree of vigor, energy, or activity. 
-------------------- 
noun 
15. living persons: the quick and the dead. 
16. the tender, sensitive flesh of the living body, especially that under the nails: nails bitten down to the quick. 
17. the vital or most important part. 
18. Chiefly British. a. a line of shrubs or plants, especially of hawthorn, forming a hedge. b. a single shrub or plant in such a hedge. 
-------------------- 
adverb 
19. quickly. 
Смежные вопросы