簡體   English   中英

Jsoup多個連接-使用已解析的URL元素

[英]Jsoup multiple connections - using already parsed element for URL

這是我的PocetnaFragment.java:

package gimbi.edu.ba;

import java.util.ArrayList;
import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.nhaarman.listviewanimations.appearance.AnimationAdapter;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.nispok.snackbar.Snackbar;
import com.software.shell.fab.ActionButton;

public class PocetnaFragment extends Fragment {

    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String SEKCIJA = "sekcija";
    static String NASLOV = "naslov";
    static String LINK = "link";
    static String SLIKA = "slika";
    // URL Address
    String url = "http://gimnazijabihac.edu.ba";

    private SwipeRefreshLayout swipeView;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_pocetna, container, false);

        listview = (ListView) view.findViewById(R.id.pocetna_listview);
        ActionButton actionButton = (ActionButton) view.findViewById(R.id.action_button);

        actionButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(!isNetworkAvailable(getActivity())) {
                    Snackbar.with(getActivity()) // context
                            .text("Neuspjela konekcija.") // text to display
                            .duration(Snackbar.SnackbarDuration.LENGTH_LONG) // make it shorter
                            .show(getActivity()); // activity where it is displayed
                } else {
                new JsoupListView().execute();
                }
            }
        });

        swipeView = (SwipeRefreshLayout) view.findViewById(R.id.pocetna_swipe);
        swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light);
        swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeView.setRefreshing(true);
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new JsoupListView().execute();
                        swipeView.setRefreshing(false);
                    }
                }, 500);
            }
        });

        if(!isNetworkAvailable(getActivity())) {
            Snackbar.with(getActivity()) // context
                    .text("Neuspjela konekcija.") // text to display
                    .duration(Snackbar.SnackbarDuration.LENGTH_LONG) // make it shorter
                    .show(getActivity()); // activity where it is displayed
        }

            new JsoupListView().execute();

        return view;
    }

    public boolean isNetworkAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();

        if (netinfo != null && netinfo.isConnectedOrConnecting()) {
            android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
            else return false;
        } else
            return false;
    }

    // Title AsyncTask
    private class JsoupListView extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_HOLO_LIGHT);
            mProgressDialog.setMessage("Učitavanje..");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            arraylist = new ArrayList<HashMap<String, String>>();
            Elements aEles = null;
            Elements divRightPostEles = null;
            String rightNaslov = null;
            Document doc = null;

            try {
                doc = Jsoup.connect(url).get();

                /** Get A tag that is under DIV with classname right_naslov **/
                aEles = doc.select("div.right_naslov > a");
                if (aEles != null && aEles.size() > 0) {
                    if (aEles.size() == 2)
                        rightNaslov = aEles.get(1).ownText();
                    else
                        rightNaslov = aEles.first().ownText();
                }

                /**
                 * Since you say there are multiple DIV with right_post as
                 * classname, we will get all those right post elements and loop
                 * them one by one to retrieve its inner elements
                 **/
                divRightPostEles = doc.select("div.right_post");

                for (Element rightPostDiv : divRightPostEles) {
                    /** Each loop of this represents a right_post DIV element **/

                    HashMap<String, String> map = new HashMap<String, String>();

                    /**
                     * Get Font tag with [classname=nadnaslov] under
                     * span[classname=right_post_nadnaslov] under
                     * div[lassname=right_post]
                     **/
                    /** Try to get Font[classname=naslov] with the following method **/
                    Elements fontNadnaslov = rightPostDiv
                            .select("span.right_post_nadnaslov > font.nadnaslov");

                    /**
                     * Get A tag that is under div[classname=right_post_tekst] under
                     * div[classname=right_post]
                     **/
                    Element aRightPostTekst = rightPostDiv.select(
                            "div.right_post_tekst > a[href]").first();

                    // Retrive Jsoup Elements
                    if (fontNadnaslov != null && fontNadnaslov.size() > 0) {
                        map.put("naslov", fontNadnaslov.first().ownText());

                        if (aRightPostTekst != null) {
                            map.put("link", aRightPostTekst.attr("href"));

                            Element img = aRightPostTekst.select("img[src]").first();

                            if (img != null)
                                map.put("slika", "http://gimnazijabihac.edu.ba/" + img.attr("src"));
                        }

                        if (rightNaslov != null)
                            map.put("sekcija", rightNaslov);
                        // Set all extracted Jsoup Elements into the array
                        arraylist.add(map);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(getActivity(), arraylist);
            AnimationAdapter animationAdapter = new SwingBottomInAnimationAdapter(adapter);
            animationAdapter.setAbsListView(listview);
            // Set the adapter to the ListView
            listview.setAdapter(animationAdapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }

}

像往常一樣,我正在AsyncTask中使用jsoup解析一些數據。 現在,我需要解析另一個包含元素或w / e的URL,例如aRightPostTekst.attr("href")

我可以在同一個asynctask中執行此操作,還是應該重新創建一個?

基本上,我需要我的網址是:

"http://url.com/" + aRightPostTekst.attr("href")

然后,我應該解析其他一些元素並放入arraylist中,然后再使用它。

是否有可能,例如多個連接並為URL使用元素?

我正在從以下網站進行解析: http://gimnazijabihac.edu.ba/ : /e-novine/n/?id=340 ,並且正在解析異步任務中的href標記,例如: /e-novine/n/?id=340 ,然后完整網址是: http://gimnazijabihac.edu.ba/e-novine/n/?id=340 : http://gimnazijabihac.edu.ba/e-novine/n/?id=340 id= http://gimnazijabihac.edu.ba/e-novine/n/?id=340

我應該從該特定網站解析html。

提前致謝。

您需要分別解析每個URL,但是您應該能夠在一個線程中進行解析(我不是Android開發人員,因此我認為AsyncTask與Thread類似)。

也代替

"http://url.com/" + aRightPostTekst.attr("href") 

您可以使用

aRightPostTekst.attr("abs:href")

得到href以絕對路徑( http://server/context/href ),而不是相對的。

您可以解析兩個URL,但是必須分別為每個URL創建一個連接,並為每個不同的URL創建一個文檔並進行相應的解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM