5

こんにちは、私は Java に比較的慣れていませんが、JSOUP を使用して HTML ファイル内のすべての ALT (画像) 属性を検索するクラスを作成したいと考えています。画像に代替テキストがなく、ユーザーに確認するように通知する場合は、エラー メッセージを出力したいと考えています。

import java.io.File;
import org.jsoup.Jsoup;
import org.jsoup.parser.Parser;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;


public class grabImages {
                File input = new File("...HTML");
                Document doc = Jsoup.parse(input, "UTF-8", "file:///C:...HTML");

                Elements img = doc.getElementsByTag("img"); 
                Elements alttext = doc.getElementsByAttribute("alt");

                 for (Element el : img){
                     if(el.attr("img").contains("alt")){
                         System.out.println("is the alt text relevant to the image? ");
                         }

                         else { System.out.println("no alt text found on image");
                         }
                    }

}       
4

3 に答える 3

6

あなたの論理は少しずれていたと思います。

例: ここでは、'img' タグの 'img' 属性を読み込もうとしています...

el.attr("img") 

これが私のプログラムの実装です。自分のニーズに合わせて変更できるはずです。

 public class Controller {

        public static void main(String[] args) throws IOException {

            // Connect to website. This can be replaced with your file loading implementation
            Document doc = Jsoup.connect("http://www.google.co.uk").get();

            // Get all img tags
            Elements img = doc.getElementsByTag("img");

            int counter = 0;

            // Loop through img tags
            for (Element el : img) {
                // If alt is empty or null, add one to counter
                if(el.attr("alt") == null || el.attr("alt").equals("")) {
                    counter++;
                }
                System.out.println("image tag: " + el.attr("src") + " Alt: " + el.attr("alt"));
            }
            System.out.println("Number of unset alt: " + counter);

        }

    }
于 2013-09-05T11:35:58.497 に答える
0

ドキュメント内のすべてを繰り返すのではなく、 CSS セレクターimgを使用してを持たないを選択することで、これを簡素化できます。altimg

    Document doc = Jsoup.connect(url).get();

    for (Element img : doc.select("img:not([alt])"))
        System.out.println("img does not have alt: " + img);
于 2016-08-01T13:06:12.523 に答える