与jsoup如何解析图像 [英] How parse image with jsoup

查看:178
本文介绍了与jsoup如何解析图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到任何这种解决方案!我需要解析与jsoup一个HTML页面,我需要解析的形象太多,但我不能做到这一点!这是我的 MainActivity

 公共类MainActivity延伸活动{
    公共静态最后弦乐TAG_TITOLI =titoli;
    私有静态最后弦乐TAG_CONTENT =内容;
    ListView的LISTA;
    静态最后弦乐BLOG_URL =htt​​p://www.multiplayer.it;
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        LISTA =(ListView控件)this.findViewById(R.id.main_lista); // recupero LISTA达ID

        //克里奥编eseguo L'的AsyncTask
        ParsingPaginaWeb解析=新ParsingPaginaWeb();
        parsing.execute();



         //启动新的页面中选择单列表项
            lista.setOnItemClickListener(新OnItemClickListener(){

                @覆盖
                公共无效onItemClick(适配器视图<>母公司视图中查看,
                        INT位置,长的id){
                    //从选择列表项获得价值
                    字符串titoli =((TextView中)view.findViewById(R.id.riga_listview_titolo))的getText()的toString()。
                    //字符串CONT =((TextView中)view.findViewById(R.id.riga_descrizione))的getText()的toString()。
                    //字符串描述=((TextView中)view.findViewById(R.id.mobile))的getText()的toString()。

                    //开始的新意图
                    意图=新的意图(getApplicationContext(),SingleActivity.class);
                    in.putExtra(TAG_TITOLI,titoli);
                    //in.putExtra(TAG_CONTENT,续);
                    //in.putExtra(TAG_PHONE_MOBILE介绍);
                    startActivity(在);

                }
            });

    }

    私有类ParsingPaginaWeb扩展的AsyncTask<字符串,字符串,字符串> {

        ArrayList的<字符串> titoli; // LISTA代titoli
        // ArrayList的<字符串>内容; // LISTA阿尔descrizioni

        @覆盖
        在preExecute保护无效()
        {
            Toast.makeText(MainActivity.this,Caricamento LISTA titoli ......,Toast.LENGTH_SHORT).show();
            //初步迪eseguire IL解析inizializzo GLI的ArrayList
            titoli =新的ArrayList<字符串>();
            //内容=新的ArrayList<字符串>();
        }

        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            尝试 {

                文档DOC = Jsoup.connect(BLOG_URL)获得();
                元件nodeBlogStats = doc.select(div.news-COL-0 H3); //每multiplayer.it元素nodeBlogStats = doc.select(div.news-COL-0 H3);每FTV #comunePartINI>选项
                对于(元sezione:nodeBlogStats)
                {
                    titoli.add(sezione.text());
                }
            }赶上(例外五){
                //在卡索二errore
                Log.e(ESEMPIO,ERRORE NEL PARSING);
            }
            返回null;
        }

        @覆盖
        保护无效onPostExecute(字符串结果)
        {
            // DOPO志和eseguito金正日解析mostro我达蒂内拉列表视图
            //山岛金正日自定义数组adpater ParsingArrayAdapter
            ParsingArrayAdapter适配器=新ParsingArrayAdapter(MainActivity.this,titoli);
            lista.setAdapter(适配器);
        }


    }

}
 

在这我可以分析的标题和dispaly他们在一个的ListView ..这是适配器:

 公共类ParsingArrayAdapter扩展ArrayAdapter<字符串> {

    // riferimenti statici全部risorseË的Agli ID
    私人最终静态INT LAYOUT = R.layout.riga_listview;
    私人最终静态INT TITOLO = R.id.riga_listview_titolo;
    //私人最终静态INT DESCRIZIONE = R.id.riga_listview_descrizione;

    ArrayList的<字符串> titoli; // LISTA代titoli

    语境℃; //上下文
    LayoutInflater充气; //布局气筒

    公共ParsingArrayAdapter(上下文的背景下,ArrayList的<字符串> titoli)
    {
        超(背景下,TITOLO);
        this.c =背景;
        this.titoli = titoli;
        this.inflater = LayoutInflater.from(C);
    }

    @覆盖
    公众诠释getCount将()
    {
        返回titoli.size(); //的Ritorno lunghezza LISTA(= NUM​​ERO代titoli)
    }

    // quando拉LISTA richiede UNA视图
    @覆盖
    公共查看getView(INT POS,视图中查看,父母的ViewGroup)
    {
        CacheRiga缓存; //缓存
        如果(查看== NULL)// SEè拉初步沃尔车viene richiesta拉视图
        {
            //克里奥拉鉴于马非L'attacco阿拉LISTA的双币种发育生物学安科拉modificare
            //我TESTI阿尔的TextView
            鉴于= inflater.inflate(布局,父母,假);
            缓存=新CacheRiga(); // inizializzo拉高速缓存
            cache.titolo =(TextView中)view.findViewById(TITOLO); // collego TITOLO
            //cache.descrizione =(TextView中)view.findViewById(DESCRIZIONE); // collego descrizione
            view.setTag(高速缓存); // collego观点CON缓存
        }
        其他
        {
            缓存=(CacheRiga)view.getTag(); // altrimenti prendo拉高速缓存DALLA视图
        }

        cache.titolo.setText(titoli.get(POS)); // imposto IL TITOLO

        返回查看;
    }

    私有类CacheRiga {// CLASSE每拉高速缓存阿尔righe
        公众的TextView TITOLO; //缓存TITOLO
        //公众的TextView descrizione; //缓存descrizione
    }

}
 

我如何可以插入每篇文章的图片吗?我不能简单地解析 DIV 图像,因为我显示字符的字符串。是有办法将其插入到列表视图?谢谢。嗯,如果需要,这是 riga_listview.xml 中,我想,我需要插入的ImageView 部分。

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>

    <的TextView
        机器人:ID =@ + ID / riga_listview_titolo
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:fontFamily中=无衬线,凝聚
        机器人:layout_margin =10dp
        机器人:textAppearance =机器人:ATTR / textAppearanceMedium/>

< / LinearLayout中>
 

解决方案

掰成片 -

  1. 获取图像的URL从div标签
  2. 显示在列表视图中的图片

现在的1,则可以使用jsoup并解析图像的URL

有关2,先添加图像视图到您的列表视图的XML 然后创建一个AsyncTask的,图像的URL传递给它和图像视图参考,并设置其在onPostExecute价值。你说的那个网站动态每次设定的图像,在这种情况下,在列表视图适配器获取视图的方法,你必须解析网页。虽然这听起来非常低效和密集的,但我不认为有任何其他方式。如果不知为何,你可以知道什么时候是图像不会改变,那么你可以做的情况下,本处理。 无论如何,这是AsyncTask的的code,从一个网址下载图像并将其设置为图像视图

 公共类ThumbnailDownloader扩展的AsyncTask<字符串,整数,位图> {

ImageView的imview;
上下文CTX;

公共ThumbnailDownloader(上下文C,ImageView的imview){
    this.imview = imview;
    this.ctx = C;
}

@覆盖
受保护的位图doInBackground(字符串...网址){
        尝试{
            HttpURLConnection的连接=(HttpURLConnection类)新的URL(getThumbUrl(网址[0]))的openConnection()。

            connection.connect();
            输入的InputStream = connection.getInputStream();
            点阵位图= BitmapFactory.de codeStream(输入);
        返回的位图;

        }
        赶上(例外F){
            // TODO自动生成的catch块
            f.printStackTrace();
        }
    返回null;
}

@覆盖
保护无效onPostExecute(位图的结果){
    // TODO自动生成方法存根
    super.onPostExecute(结果);
    如果(结果= NULL和放大器;!&安培; imview!= NULL){
        imview.setImageBitmap(结果);
    }
}

公共字符串getThumbUrl(字符串videoUrl){
    返回http://img.youtube.com/vi/"+videoUrl+"/default.jpg;
}
}
 

该getThumbUrl方法,你可以根据自己的需要修改。 上面指定的一个是用来下载YouTube视频缩略图。

I can't find any solution for this!! I need parsing a html page with jsoup and i need parse the image too but i can't do it! This is my MainActivity

public class MainActivity extends Activity {
    public static final String TAG_TITOLI = "titoli";
    private static final String TAG_CONTENT = "content";
    ListView lista;
    static final String BLOG_URL = "http://www.multiplayer.it";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lista = (ListView)this.findViewById(R.id.main_lista);//recupero lista da id

        //creo ed eseguo l'asynctask
        ParsingPaginaWeb parsing = new ParsingPaginaWeb();
        parsing.execute("");



         // Launching new screen on Selecting Single ListItem
            lista.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting values from selected ListItem
                    String titoli = ((TextView) view.findViewById(R.id.riga_listview_titolo)).getText().toString();
                    //String cont = ((TextView) view.findViewById(R.id.riga_descrizione)).getText().toString();
                    //String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

                    // Starting new intent
                    Intent in = new Intent(getApplicationContext(), SingleActivity.class);
                    in.putExtra(TAG_TITOLI, titoli);
                    //in.putExtra(TAG_CONTENT, cont);
                    //in.putExtra(TAG_PHONE_MOBILE, description);
                    startActivity(in);

                }
            });

    }

    private class ParsingPaginaWeb extends AsyncTask<String,String,String> {

        ArrayList<String> titoli; //lista dei titoli
        //ArrayList<String> content; //lista delle descrizioni

        @Override
        protected void onPreExecute()
        {   
            Toast.makeText(MainActivity.this ,"Caricamento lista titoli...", Toast.LENGTH_SHORT).show();
            //prima di eseguire il parsing inizializzo gli arraylist
            titoli = new ArrayList<String>();
            //content = new ArrayList<String>();
        }

        @Override
        protected String doInBackground(String... params) {
            try {

                Document doc = Jsoup.connect(BLOG_URL).get();
                Elements nodeBlogStats = doc.select("div.news-col-0 h3"); //per multiplayer.it Elements nodeBlogStats = doc.select("div.news-col-0 h3"); per ftv #comunePartINI > option
                for(Element sezione : nodeBlogStats)
                {
                    titoli.add(sezione.text());
                }
            } catch (Exception e) {
                // In caso di errore
                Log.e("ESEMPIO", "ERRORE NEL PARSING");
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            // dopo che ho eseguito il parsing mostro i dati nella listview
            // usando il custom array adpater ParsingArrayAdapter
            ParsingArrayAdapter adapter = new ParsingArrayAdapter(MainActivity.this, titoli);
            lista.setAdapter(adapter);
        }


    }

}

In which i can parse the titles and dispaly them in a ListView.. This is the Adapter:

public class ParsingArrayAdapter extends ArrayAdapter<String>{

    //riferimenti statici alle risorse e agli id
    private final static int LAYOUT = R.layout.riga_listview;
    private final static int TITOLO = R.id.riga_listview_titolo;
    //private final static int DESCRIZIONE = R.id.riga_listview_descrizione;

    ArrayList<String> titoli; //lista dei titoli

    Context c; //context
    LayoutInflater inflater; //layout inflater

    public ParsingArrayAdapter(Context context,ArrayList<String> titoli)
    {
        super(context,TITOLO);
        this.c = context;
        this.titoli = titoli;
        this.inflater = LayoutInflater.from(c);
    }

    @Override
    public int getCount()
    {
        return titoli.size(); //ritorno lunghezza lista ( = numero dei titoli)
    }

    //quando la lista richiede una view
    @Override
    public View getView(int pos,View view,ViewGroup parent)
    {
        CacheRiga cache; //cache
        if(view==null)//se è la prima volta che viene richiesta la view
        {
            // creo la view ma non l'attacco alla lista in quanto devo ancora modificare
            // i testi delle textview
            view = inflater.inflate(LAYOUT, parent,false); 
            cache = new CacheRiga(); //inizializzo la cache
            cache.titolo = (TextView) view.findViewById(TITOLO); //collego titolo
            //cache.descrizione = (TextView) view.findViewById(DESCRIZIONE);//collego descrizione
            view.setTag(cache);//collego view con cache
        }
        else
        {
            cache = (CacheRiga) view.getTag(); //altrimenti prendo la cache dalla view
        }

        cache.titolo.setText(titoli.get(pos)); //imposto il titolo

        return view;
    }

    private class CacheRiga { // classe per la cache delle righe
        public TextView titolo; // cache titolo
        //public TextView descrizione; // cache descrizione
    }

}

How can i insert the images for each article? I can't simply parse the div of image because i display a string of characters.. Is there a way to insert it in the listview? Thanks. Ah if needs, this is the riga_listview.xml in which, i suppose, i need insert the ImageView part.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/riga_listview_titolo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:layout_margin="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

解决方案

Break it into pieces -

  1. Get the url of the image from div tag
  2. Show that image in the list view

Now for "1", you can use jsoup and parse the url of the image

For "2", first add image view to your list view xml Then create an asynctask, pass image url to it and reference of image view and set its value in onPostExecute. You said that website sets image dynamically, in that case every time on the get view method of list view adapter, you have to parse the webpage. Although this sounds very inefficient and intensive, but I don't think there is any other way. If somehow you can know when is the image going to change, then you can do this processing on that event. Anyway, this is the code of the asynctask to download the image from a url and set it to image view

public class ThumbnailDownloader extends AsyncTask<String, Integer, Bitmap>{

ImageView imview;
Context ctx;

public ThumbnailDownloader(Context c, ImageView imview){
    this.imview = imview;
    this.ctx = c;
}

@Override
protected Bitmap doInBackground(String... urls) {
        try{
            HttpURLConnection connection = (HttpURLConnection)new URL(getThumbUrl(urls[0])).openConnection();

            connection.connect();
            InputStream input= connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

        }
        catch (Exception f) {
            // TODO Auto-generated catch block
            f.printStackTrace();
        }
    return null;
}

@Override
protected void onPostExecute(Bitmap result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    if(result != null && imview!=null){
        imview.setImageBitmap(result);
    }
}

public String getThumbUrl(String videoUrl){
    return "http://img.youtube.com/vi/"+videoUrl+"/default.jpg";
}
}

The getThumbUrl method you have to modify according to your need. The one specified above is used to download youtube video thumbnails.

这篇关于与jsoup如何解析图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆