Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取JSOUP上的索引不起作用_Java_Android_Attributes_Jsoup - Fatal编程技术网

Java 获取JSOUP上的索引不起作用

Java 获取JSOUP上的索引不起作用,java,android,attributes,jsoup,Java,Android,Attributes,Jsoup,我试着调试了几次,但我一直收到错误,线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:-1我也不确定为什么会发生这种情况?有人能告诉我哪里出了问题吗?您正在从所有div类中提取样式属性字符串=“chart-row__image元素,但请理解此组中的许多元素没有样式属性。在这种情况下,JSoup将返回一个空字符串,这将打乱您的程序。解决方案不是这样做,而是让jsoup只选择那些具有style属性的元素 例如,不是: tr

我试着调试了几次,但我一直收到错误,
线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:-1
我也不确定为什么会发生这种情况?有人能告诉我哪里出了问题吗?

您正在从所有
div类中提取样式属性字符串=“chart-row__image
元素,但请理解此组中的许多元素没有样式属性。在这种情况下,JSoup将返回一个空字符串,这将打乱您的程序。解决方案不是这样做,而是让jsoup只选择那些具有style属性的元素

例如,不是:

try {
    String url = "http://www.billboard.com/charts/artist-100";
    String urlFound;
    String closing = ")";
    String start = "h";
    Document doc = Jsoup.connect(url).get();
    Elements urls = doc.getElementsByClass("chart-row__image");
    for (Element u : urls) {
        urlFound = u.attr("style");
        String sub =  urlFound.substring(urlFound.indexOf(start), urlFound.indexOf(closing));
        System.out.println(sub);
        //Log.d("URLS,", attr.substring(attr.indexOf("http://"), attr.indexOf(")")));
    }
}
catch(IOException ex){
}
而是:

Elements urls = doc.getElementsByClass("chart-row__image");
是的,不要忽略例外情况

所以

Elements urls = doc.select(".chart-row__image[style]");
    String url = "http://www.billboard.com/charts/artist-100";
    String urlFound;
    String closing = ")";
    String start = "h";
    Document doc;
    try {
        doc = Jsoup.connect(url).get();
        // Elements urls = doc.getElementsByClass("chart-row__image");
        Elements urls = doc.select(".chart-row__image[style]");
        for (Element u : urls) {
            urlFound = u.attr("style");
            int startingIndex = urlFound.indexOf(start);
            int endingIndex = urlFound.indexOf(closing);
            if (startingIndex > 0 && endingIndex > 0) {
                String sub = urlFound.substring(startingIndex, endingIndex);
                System.out.println(sub);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }