无法使用 jsoup 获取准确的图像和文本

如何解决无法使用 jsoup 获取准确的图像和文本

我想从以下网站获取图像 URL 和标题。我到处搜索并尝试了许多 jsoup 代码,但我无法获得确切的图像和标题。我已在清单文件中添加了 Internet 权限并添加了依赖项。

https://www.forbesindia.com/lists/2015-celebrity-100/1519/1

Website source screenshoot

到目前为止我已经尝试过这个

  new Thread(new Runnable()
        {
            //final EbayProduct product = new EbayProduct();
            @Override
            public void run()
            {
                try
                {
                    Document doc = Jsoup.connect("https://www.forbesindia.com/lists/2015-celebrity-100/1519/1").get();
                    Elements body = doc.getAllElements();
                    //System.out.println(body.select("tr").size());
                   // Log.i("Size",Integer.toString(body.select("td").size()));

                    for(Element e : body.select("img"))
                    {
                        String image = e.select(" img").attr("src");
                        String title = e.select("img").attr("alt");
                        celebURLs.add(image);
                        celebNames.add(title);
                        Log.i("bal",String.valueOf(celebURLs));
                        Log.i("bal2",String.valueOf(celebNames));
                    }

                    newQuestion();

                }catch (Exception ex){
   ex.printStackTrace();
                }


            }
        }).start();

这会提供来自网站而非列表的随机图像。

Logcat

2021-05-04 22:46:00.904 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png]
2021-05-04 22:46:00.904 25418-25548/com.example.guessthecelebrity I/bal2: []
2021-05-04 22:46:00.904 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/list/banner/list_1519.jpg]
2021-05-04 22:46:00.905 25418-25548/com.example.guessthecelebrity I/bal2: [,2015 Celebrity 100 - Forbes India Magazine]
2021-05-04 22:46:00.905 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/list/banner/list_1519.jpg,https://www.forbesindia.com/media/sectionimage/header/30under30_21_230_20210203091422_230x62.jpg]
2021-05-04 22:46:00.905 25418-25548/com.example.guessthecelebrity I/bal2: [,2015 Celebrity 100 - Forbes India Magazine,]
2021-05-04 22:46:00.906 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/30under30_21_230_20210203091422_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/managers_230_20201013010335_230x62.jpg]
2021-05-04 22:46:00.906 25418-25548/com.example.guessthecelebrity I/bal2: [,https://www.forbesindia.com/media/sectionimage/header/managers_230_20201013010335_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/forbesindia_richlist_sc230_20201008054355_230x62.jpg]
2021-05-04 22:46:00.906 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.907 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/forbesindia_richlist_sc230_20201008054355_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/wpower_2020_1_20200303061653_230x62.jpg]
2021-05-04 22:46:00.907 25418-25548/com.example.guessthecelebrity I/bal2: [,https://www.forbesindia.com/media/sectionimage/header/wpower_2020_1_20200303061653_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/30under30_section_sm_20200205082639_230x62.jpg]
2021-05-04 22:46:00.908 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.908 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/30under30_section_sm_20200205082639_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/celeb19_sm_20191219030109_230x62.jpg]
2021-05-04 22:46:00.909 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.909 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/celeb19_sm_20191219030109_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/richlist2019_230_20191011022510_230x62.jpg]
2021-05-04 22:46:00.909 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.910 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/richlist2019_230_20191011022510_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/wpower2019_230_20190301085545_230x62.jpg]
2021-05-04 22:46:00.910 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.911 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/wpower2019_230_20190301085545_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/30under30_2019_sm1_20190204072937_230x62.jpg]
2021-05-04 22:46:00.911 25418-25548/com.example.guessthecelebrity I/bal2: [,https://www.forbesindia.com/media/sectionimage/header/30under30_2019_sm1_20190204072937_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/celeb18_sm_20181205054447_230x62.jpg]
2021-05-04 22:46:00.912 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.913 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/celeb18_sm_20181205054447_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/richlistsection_sm_20181004054854_230x62.jpg]
2021-05-04 22:46:00.913 25418-25548/com.example.guessthecelebrity I/bal2: [,]
2021-05-04 22:46:00.914 25418-25548/com.example.guessthecelebrity I/bal: [https://www.forbesindia.com/forbes-rvp-files/images/forbes-logo.png,https://www.forbesindia.com/media/sectionimage/header/richlistsection_sm_20181004054854_230x62.jpg,https://www.forbesindia.com/media/sectionimage/header/supper50_sm_20180821013603_230x62.jpg]
2021-05-04 22:46:00.914 25418-25548/com.example.guessthecelebrity I/bal2: [,]


我得到的是图片网址和标题,但不是 100 个名人图片网址和标题。

完整的java文件

package com.example.guessthecelebrity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

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

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {




    ArrayList<String> celebURLs = new ArrayList<String>();
    ArrayList<String> celebNames = new ArrayList<String>();
    int chosenCeleb = 0;
    String[] answers = new String[4];
    int locationOfCorrectAnswer = 0;
    ImageView imageView;
    Button button0;
    Button button1;
    Button button2;
    Button button3;

    public void celebChosen(View view) {
        Log.i("bal","celebchosen");
        if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
            Toast.makeText(getApplicationContext(),"Correct!",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(),"Worng! It was " + celebNames.get(chosenCeleb),Toast.LENGTH_SHORT).show();
        }

        newQuestion();
    }

    public class ImageDownloader extends AsyncTask<String,Void,Bitmap> {

        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                Log.i("bal","imagedownloader");
                URL url = new URL(urls[0]);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
                return myBitmap;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    public class DownloadTask extends AsyncTask<String,String> {

        @Override
        protected String doInBackground(String... urls) {

            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                Log.i("bal","downloadTask");

                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection) url.openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();

                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }

                return result;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

        }
    }

    public void newQuestion() {
        try {
            Log.i("bal","newQuestion");

            Random rand = new Random();

            chosenCeleb = rand.nextInt(celebURLs.size());

            ImageDownloader imageTask = new ImageDownloader();

            Bitmap celebImage = imageTask.execute(celebURLs.get(chosenCeleb)).get();

            imageView.setImageBitmap(celebImage);

            locationOfCorrectAnswer = rand.nextInt(4);

            int incorrectAnswerLocation;

            for (int i = 0; i < 4; i++) {
                if (i == locationOfCorrectAnswer) {
                    answers[i] = celebNames.get(chosenCeleb);
                } else {
                    incorrectAnswerLocation = rand.nextInt(celebURLs.size());

                    while (incorrectAnswerLocation == chosenCeleb) {
                        incorrectAnswerLocation = rand.nextInt(celebURLs.size());
                    }

                    answers[i] = celebNames.get(incorrectAnswerLocation);
                }
            }

            button0.setText(answers[0]);
            button1.setText(answers[1]);
            button2.setText(answers[2]);
            button3.setText(answers[3]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        button0 = findViewById(R.id.button0);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);

        DownloadTask task = new DownloadTask();
        String result = null;
        Log.i("bal","Works");

         new Thread(new Runnable()
        {
            //final EbayProduct product = new EbayProduct();
            @Override
            public void run()
            {
                try
                {
                    Document doc = Jsoup.connect("https://www.forbesindia.com/lists/2015-celebrity-100/1519/1").get();
                    Elements body = doc.getAllElements();
                    //System.out.println(body.select("tr").size());
                   // Log.i("Size",String.valueOf(celebNames));
                    }

                    newQuestion();

                }catch (Exception ex){
   ex.printStackTrace();
                }


            }
        }).start();
    }
}

XML 文件

  <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#151414"
   tools:context=".MainActivity">

   <ImageView
       android:id="@+id/imageView"
       android:layout_width="0dp"
       android:layout_height="0dp"
       android:layout_marginStart="10dp"
       android:layout_marginTop="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:scaleType="fitCenter"
       app:layout_constraintBottom_toTopOf="@+id/button0"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent"
       app:srcCompat="@android:color/holo_blue_bright" />

   <Button
       android:id="@+id/button3"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:onClick="celebChosen"
       android:tag="3"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent" />

   <Button
       android:id="@+id/button2"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:onClick="celebChosen"
       android:tag="2"
       app:layout_constraintBottom_toTopOf="@+id/button3"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintHorizontal_bias="0.0"
       app:layout_constraintStart_toStartOf="parent" />

   <Button
       android:id="@+id/button1"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:onClick="celebChosen"
       android:tag="1"
       app:layout_constraintBottom_toTopOf="@+id/button2"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintHorizontal_bias="0.0"
       app:layout_constraintStart_toStartOf="parent" />

   <Button
       android:id="@+id/button0"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:layout_marginStart="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:onClick="celebChosen"
       android:tag="0"
       app:layout_constraintBottom_toTopOf="@+id/button1"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintHorizontal_bias="0.0"
       app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res