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 (将#修改为@)