Example usage for org.jsoup.select Elements attr

List of usage examples for org.jsoup.select Elements attr

Introduction

In this page you can find the example usage for org.jsoup.select Elements attr.

Prototype

public String attr(String attributeKey) 

Source Link

Document

Get an attribute value from the first matched element that has the attribute.

Usage

From source file:com.normalexception.app.rx8club.fragment.pm.PrivateMessageViewFragment.java

/**
 * Construct the view elements/*from   w w w  .  ja v  a 2 s . co m*/
 */
private void constructView() {
    AsyncTask<Void, String, Void> updaterTask = new AsyncTask<Void, String, Void>() {
        @Override
        protected void onPreExecute() {

            loadingDialog = ProgressDialog.show(getActivity(), getString(R.string.loading),
                    getString(R.string.pleaseWait), true);
        }

        @Override
        protected Void doInBackground(Void... params) {
            String link = getArguments().getString("link");
            Document doc = VBForumFactory.getInstance().get(getActivity(),
                    VBForumFactory.getRootAddress() + "/" + link);

            if (doc != null) {
                securityToken = HtmlFormUtils.getInputElementValueByName(doc, "securitytoken");

                pmid = HtmlFormUtils.getInputElementValueByName(doc, "pmid");

                title = HtmlFormUtils.getInputElementValueByName(doc, "title");

                Elements userPm = doc.select("table[id^=post]");
                publishProgress(getString(R.string.asyncDialogLoadingPM));

                // User Control Panel
                Elements userCp = userPm.select("td[class=alt2]");
                Elements userDetail = userCp.select("div[class=smallfont]");
                Elements userSubDetail = userDetail.last().select("div");
                Elements userAvatar = userDetail.select("img[alt$=Avatar]");
                Elements postMessage = doc.select("div[id=post_message_]");

                PMPostModel pv = new PMPostModel();
                pv.setUserName(userCp.select("div[id^=postmenu]").text());
                pv.setIsLoggedInUser(LoginFactory.getInstance().isLoggedIn()
                        ? UserProfile.getInstance().getUsername().equals(pv.getUserName())
                        : false);
                pv.setUserTitle(userDetail.first().text());
                pv.setUserImageUrl(Utils.resolveUrl(userAvatar.attr("src")));
                pv.setPostDate(userPm.select("td[class=thead]").first().text());

                // userSubDetail
                // 0 - full container , full container
                // 1 - Trader Score   , Trader Score
                // 2 - Join Date      , Join Date
                // 3 - Post Count     , Location
                // 4 - Blank          , Post Count
                // 5 -                , Blank || Social
                //
                Iterator<Element> itr = userSubDetail.listIterator();
                while (itr.hasNext()) {
                    String txt = itr.next().text();
                    if (txt.contains("Location:"))
                        pv.setUserLocation(txt);
                    else if (txt.contains("Posts:"))
                        pv.setUserPostCount(txt);
                    else if (txt.contains("Join Date:"))
                        pv.setJoinDate(txt);
                }

                // User Post Content
                pv.setUserPost(formatUserPost(postMessage));

                pmlist.add(pv);

                TextView comment = (TextView) getView().findViewById(R.id.pmitem_comment);
                Elements textarea = doc.select("textarea[id=vB_Editor_QR_textarea]");
                if (textarea != null) {
                    comment.setText(textarea.first().text());
                }

                updateList();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... progress) {
            if (loadingDialog != null)
                loadingDialog.setMessage(progress[0]);
        }

        @Override
        protected void onPostExecute(Void result) {
            try {
                loadingDialog.dismiss();
                loadingDialog = null;
            } catch (Exception e) {
                Log.w(TAG, e.getMessage());
            }
        }
    };
    updaterTask.execute();
}

From source file:com.normalexception.app.rx8club.fragment.ProfileFragment.java

/**
 * Get the user information from the users profile
 * @param doc   The page document/* w  w w . ja v a2  s  .co  m*/
 */
private void getUserInformation(Document doc) {
    final UserProfile upInstance = UserProfile.getInstance();
    stubs = new ArrayList<ProfileModel>();

    // Title
    Elements userInfo = doc.select("div[id=main_userinfo]");
    Elements title = userInfo.select("h2");
    upInstance.setUserTitle(title.text());

    // Posts
    Elements statisticInfo = doc.select("fieldset[class=statistics_group]");
    Elements post = statisticInfo.select("li");

    // Profile Pic
    Elements profilePicInfo = doc.select("td[id=profilepic_cell] > img");

    // Grab image, trap
    try {
        upInstance.setUserImageLink(profilePicInfo.attr("src"));
    } catch (Exception e) {
    }

    // Grab Post count, trap exception
    try {
        upInstance.setUserPostCount(
                post.get(0).text() + " / " + post.get(1).text().split(" ", 4)[3] + " per day");
    } catch (Exception e) {
        upInstance.setUserPostCount("Error Getting Post Count");
    }

    // Grab Join Date, trap exception
    try {
        upInstance.setUserJoinDate(post.get(13).text());
    } catch (Exception e) {
        upInstance.setUserJoinDate("Error Getting Join Date");
    }

    // Threads
    String link = WebUrls.userUrl + upInstance.getUserId();
    doc = VBForumFactory.getInstance().get(getActivity(), link);
    if (doc != null) {
        Elements threadlist = doc.select("table[id^=post]");
        for (Element threadl : threadlist) {
            ProfileModel stub = new ProfileModel();
            Elements divs = threadl.getElementsByTag("div");
            Elements div = divs.get(1).getElementsByTag("a");
            stub.setLink(div.attr("href"));
            stub.setName(div.text());

            div = divs.get(5).getElementsByTag("a");
            stub.setText(div.text());
            stubs.add(stub);
        }
    }
}

From source file:com.normalexception.app.rx8club.fragment.thread.ThreadFragment.java

/**
 * Grab contents from the forum that the user clicked on
 * @param doc   The document parsed from the link
 * @param id   The id number of the link
 * @return      An arraylist of forum contents
 *///from   ww w .java 2  s .c o m
public void getThreadContents(Document doc) {
    // Update pagination
    try {
        Elements pageNumbers = doc.select("div[class=pagenav]");
        if (pageNumbers.first() != null) {
            Elements pageLinks = pageNumbers.first().select("td[class^=vbmenu_control]");
            thisPage = pageLinks.text().split(" ")[1];
            finalPage = pageLinks.text().split(" ")[3];
            Log.d(TAG, String.format("This Page: %s, Final Page: %s", thisPage, finalPage));
        } else {
            Log.d(TAG, "Thread only contains one page");
        }
    } catch (Exception e) {
        Log.e(TAG, "We had an error with pagination", e);
    }

    // Is user thread admin??
    Elements threadTools = doc.select("div[id=threadtools_menu] > form > table");
    if (threadTools.text().contains(MODERATION_TOOLS)) {
        Log.d(TAG, "<><> User has administrative rights here! <><>");
    } else {
        //adminContent.setVisibility(View.GONE);
        lv.removeHeaderView(adminContent);
    }

    // Get the user's actual ID, there is a chance they never got it
    // before
    UserProfile.getInstance().setUserId(HtmlFormUtils.getInputElementValueByName(doc, "loggedinuser"));

    // Get Post Number and security token
    securityToken = HtmlFormUtils.getInputElementValueByName(doc, "securitytoken");

    Elements pNumber = doc.select("a[href^=http://www.rx8club.com/newreply.php?do=newreply&noquote=1&p=]");
    String pNumberHref = pNumber.attr("href");
    postNumber = pNumberHref.substring(pNumberHref.lastIndexOf("=") + 1);
    threadNumber = doc.select("input[name=searchthreadid]").attr("value");

    Elements posts = doc.select("div[id=posts]").select("div[id^=edit]");
    Log.v(TAG, String.format("Parsing through %d posts", posts.size()));
    for (Element post : posts) {
        try {
            Elements innerPost = post.select("table[id^=post]");

            // User Control Panel
            Elements userCp = innerPost.select("td[class=alt2]");
            Elements userDetail = userCp.select("div[class=smallfont]");
            Elements userSubDetail = userDetail.last().select("div");
            Elements userAvatar = userDetail.select("img[alt$=Avatar]");

            // User Information
            PostModel pv = new PostModel();
            pv.setUserName(userCp.select("div[id^=postmenu]").text());
            pv.setIsLoggedInUser(LoginFactory.getInstance().isLoggedIn()
                    ? UserProfile.getInstance().getUsername().equals(pv.getUserName())
                    : false);
            pv.setUserTitle(userDetail.first().text());
            pv.setUserImageUrl(userAvatar.attr("src"));
            pv.setPostDate(innerPost.select("td[class=thead]").first().text());
            pv.setPostId(Utils.parseInts(post.attr("id")));
            pv.setRootThreadUrl(currentPageLink);

            // get Likes if any exist
            Elements eLikes = innerPost.select("div[class*=vbseo_liked] > a");
            List<String> likes = new ArrayList<String>();
            for (Element eLike : eLikes)
                likes.add(eLike.text());
            pv.setLikes(likes);

            Iterator<Element> itr = userSubDetail.listIterator();
            while (itr.hasNext()) {
                String txt = itr.next().text();
                if (txt.contains("Location:"))
                    pv.setUserLocation(txt);
                else if (txt.contains("Posts:"))
                    pv.setUserPostCount(txt);
                else if (txt.contains("Join Date:"))
                    pv.setJoinDate(txt);
            }

            // User Post Content
            pv.setUserPost(formatUserPost(innerPost));

            // User signature
            try {
                Element userSig = innerPost.select("div[class=konafilter]").first();
                pv.setUserSignature(userSig.html());
            } catch (NullPointerException npe) {
            }

            Elements postAttachments = innerPost.select("a[id^=attachment]");
            if (postAttachments != null && !postAttachments.isEmpty()) {
                ArrayList<String> attachments = new ArrayList<String>();
                for (Element postAttachment : postAttachments) {
                    attachments.add(postAttachment.attr("href"));
                }
                pv.setAttachments(attachments);
            }

            pv.setSecurityToken(securityToken);

            // Make sure we aren't adding a blank user post
            if (pv.getUserPost() != null)
                postlist.add(pv);
        } catch (Exception e) {
            Log.w(TAG, "Error Parsing Post...Probably Deleted");
        }
    }
}

From source file:org.aankor.animenforadio.api.WebsiteGate.java

private boolean updateNowPlaying(String nowPlaying) {
    Document doc = Jsoup.parse(nowPlaying);

    Elements spans = doc.select("div .float-container .row .span6");

    Matcher matcher = mainNowPlayingPattern.matcher(spans.first().text());

    if (!matcher.find()) {
        unsetCurrentSong();/*from   w w w. j  a  va 2 s  .  c om*/
        return false;
    }
    SongInfo newSongInfo = new SongInfo(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4),
            matcher.group(5), matcher.group(6));

    Elements e = doc.select("div img");
    if (!e.isEmpty()) {
        String artUrl = e.attr("src");
        newSongInfo.setArtUrl(artUrl);
    } else
        newSongInfo.unsetArtUrl();

    newSongInfo.setSongId(Integer.valueOf(spans.get(1).select("a[data-songinfo]").attr("data-songinfo")));

    int songPosTime = Integer.valueOf(spans.get(1).select("#np_timer").attr("rel"));
    long currentTime = (new Date()).getTime();
    currentSongEndTime = currentTime + songPosTime * 1000l;
    String songPosTimeStr = spans.get(1).select("#np_timer").text();
    newSongInfo.setDuration(Integer.valueOf(spans.get(1).select("#np_time").attr("rel")));
    newSongInfo.setDurationStr(spans.get(1).select("#np_time").text());

    matcher = raitingNowPlayingPattern.matcher(spans.get(1).html());

    if (matcher.find())
        newSongInfo.setRating(matcher.group(1));
    else
        newSongInfo.unsetRating();

    newSongInfo.setFavourites(Integer.valueOf(spans.get(1)
            .select(".favourite-container span[data-favourite-count]").attr("data-favourite-count")));

    matcher = nowPlayingBarPattern.matcher(doc.select("#nowPlayingBar").attr("style"));
    double nowPlayingPos = 0.0;
    if (matcher.find())
        nowPlayingPos = Double.valueOf(matcher.group(1));

    if ((currentSong != null) && newSongInfo.getArtUrl().equals(currentSong.getArtUrl()))
        newSongInfo.setArtBmp(currentSong.getArtBmp(), currentSong.getMiniArtBmp());
    currentSong = newSongInfo;
    currentSongPos = new SongPos(songPosTime, songPosTimeStr, nowPlayingPos);
    return true;
}

From source file:org.aliuge.crawler.extractor.selector.AbstractElementCssSelector.java

/**
 * ??????//from w w  w .  ja v a  2 s  . c  o  m
 * @param elements
 * @param attr
 * @return
 */
protected String getExtractAttr(Elements elements, String attr) {
    String temp = "";
    if (attr.equalsIgnoreCase("tostring")) {
        return temp = elements.attr(attr).toString();
    } else {
        if (index == -1 && StringUtils.isNotBlank(this.regex)) {
            for (Element e : elements) {
                Element element = e;
                if (element.select(this.regex).size() > 0) {
                    return temp = e.attr(attr);
                }
            }
            return temp;
        } else {
            if (index > -1 && index < elements.size()) {
                return elements.get(index).attr(attr);
            }
        }
        return elements.first().attr(attr);
    }
    /*if(null!=pattern){
       Matcher m = pattern.matcher(temp);
       if(m.find()){
    temp = m.group(1);
       }
    }*/
    //return temp;
}

From source file:org.openmrs.module.radiology.report.template.DefaultMrrtReportTemplateFileParser.java

private final void initializeTemplate(MrrtReportTemplate template, Document doc) {
    final Elements metaTags = doc.getElementsByTag("meta");

    template.setPath(doc.baseUri());/*from   w w w .j  a va 2 s  . c om*/
    template.setCharset(metaTags.attr("charset"));
    for (Element metaTag : metaTags) {
        final String name = metaTag.attr("name");
        final String content = metaTag.attr("content");

        switch (name) {
        case DCTERMS_TITLE:
            template.setDcTermsTitle(content);
            break;
        case DCTERMS_DESCRIPTION:
            template.setDcTermsDescription(content);
            break;
        case DCTERMS_IDENTIFIER:
            template.setDcTermsIdentifier(content);
            break;
        case DCTERMS_TYPE:
            template.setDcTermsType(content);
            break;
        case DCTERMS_LANGUAGE:
            template.setDcTermsLanguage(content);
            break;
        case DCTERMS_PUBLISHER:
            template.setDcTermsPublisher(content);
            break;
        case DCTERMS_RIGHTS:
            template.setDcTermsRights(content);
            break;
        case DCTERMS_LICENSE:
            template.setDcTermsLicense(content);
            break;
        case DCTERMS_DATE:
            template.setDcTermsDate(content);
            break;
        case DCTERMS_CREATOR:
            template.setDcTermsCreator(content);
            break;
        default:
            log.debug("Unhandled meta tag " + name);
        }
    }
}

From source file:org.thorn.emma.model.Html.java

public String fetchAttr(String selector, String attr) {
    Elements elements = this.document.select(selector);
    return elements.attr(attr);
}

From source file:Records.Attributes.BeatportInfoRetriever.java

/**
 * Start connection./*  w ww  .ja  v a2 s .c  o m*/
 *
 * @param title
 *          the title
 * @param artist
 *          the artist
 */
private static JSONObject getBeatportObject(String site) {
    System.out.println("BeatportInfoRetriever.startConnection(" + site + ")");
    JSONObject objectInArray;
    try {
        Document doc = Jsoup.connect(site).get();
        Elements link = doc.select("span[class = play-queue play-queue-med-small]");
        String musicLink = link.attr("data-json");
        objectInArray = new JSONObject(musicLink);
    } catch (IOException | JSONException ex) {
        System.err.println("Error Connecting to Beatport");
        objectInArray = null;
    }
    return objectInArray;
}