微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

htmlunit在循环中选择错误的对象

如何解决htmlunit在循环中选择错误的对象

我正在使用 HTMLunit 在 Java 中创建一个简单的网页抓取工具,这是代码

try {
            HtmlPage page=client.getPage(url);
            List<HtmlElement> items = page.getByXPath("//li[@class='work blurb group']");;
            System.out.println(items);
            if (items.isEmpty()){
                System.out.println("list is empty");
            } else{
                for(HtmlElement htmlItem : items){
                    System.out.println(htmlItem.getTextContent());
                    HtmlElement rating = htmlItem.getFirstByXPath("//span[@class='text']");
                    HtmlElement hits = htmlItem.getFirstByXPath("//dd[@class='hits']");
                    HtmlElement language = htmlItem.getFirstByXPath("//dd[@class='language']");
                    HtmlElement words = htmlItem.getFirstByXPath("//dd[@class='words']");
                    System.out.println("this is the rating: " + rating.getTextContent());
                    System.out.println("this is the hits: " + hits.getTextContent());
                    System.out.println("this is the language: "+ language.getTextContent());
                    System.out.println("this is the words: "+words.getTextContent());
                    FanFic fanfic= new FanFic(Integer.parseInt(hits.getTextContent()),rating.getTextContent(),Integer.parseInt(words.getTextContent().replace(",","")),language.getTextContent());
                    ObjectMapper mapper = new ObjectMapper();
                    String jsonString = mapper.writeValueAsstring(fanfic);
                    System.out.println(jsonString);
                }
            }

        } catch (IOException e) {
            e.printstacktrace();
}

对于列表中的第一个对象,它正确选择了我要查找的值,但是在第二次迭代中,它打印出我有正确的 li 对象,但是当我尝试提取特定的'hits,language,rating and words'值,出于某种原因仍然从第一个对象中提取值

我不确定我在这里做错了什么: 这些是从我的打印行中打印出来的第一个对象,然后是第二个对象:

First item,which is correct

Second which is wrong

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