【问题标题】:Read a specified line of text from a webpage with Jsoup使用 Jsoup 从网页中读取指定的文本行
【发布时间】:2016-07-24 02:55:33
【问题描述】:

所以我正在尝试使用 Jsoup 从this webpage 获取数据...

我尝试了很多不同的方法,我已经接近了,但我不知道如何找到某些统计数据的标签(AttackStrength em>、防御等)

所以假设为了示例,我想打印出来

'Attack', '15', '99', '200,000,000' 

我该怎么做呢?

【问题讨论】:

  • 尽量让你的问题更清楚,并表现出足够的研究努力。否则你不会在这里得到太多帮助。在提出下一个问题之前,请阅读stackoverflow.com/help/how-to-ask

标签: java html jsoup screen-scraping


【解决方案1】:

您可以在Jsoup 中使用CSS selectors 轻松提取列数据。

// retrieve page source code
Document doc = Jsoup
        .connect("http://services.runescape.com/m=hiscore_oldschool/hiscorepersonal.ws?user1=Lynx%A0Titan")
        .get();

// find all of the table rows
Elements rows = doc.select("div#contentHiscores table tr");
ListIterator<Element> itr = rows.listIterator();

// loop over each row
while (itr.hasNext()) {
    Element row = itr.next();

    // does the second col contain the word attack?
    if (row.select("td:nth-child(2) a:contains(attack)").first() != null) {

        // if so, assign each sibling col to variable
        String rank = row.select("td:nth-child(3)").text();
        String level = row.select("td:nth-child(4)").text();
        String xp = row.select("td:nth-child(5)").text();

        System.out.printf("rank=%s level=%s xp=%s", rank, level, xp);

        // stop looping rows, found attack
        break;
    }
}

【讨论】:

    【解决方案2】:

    一个非常粗略的实现如下。我刚刚展示了一个 sn-p ,需要添加优化或其他条件

        public static void main(String[] args) throws Exception {
        Document doc = Jsoup
                .connect("http://services.runescape.com/m=hiscore_oldschool/hiscorepersonal.ws?user1=Lynx%A0Titan")
                .get();
        Element contentHiscoresDiv = doc.getElementById("contentHiscores");
        Element table = contentHiscoresDiv.child(0);
        for (Element row : table.select("tr")) {
            Elements tds = row.select("td");
            for (Element column : tds) {
                if (column.children() != null && column.children().size() > 0) {
                    Element anchorTag = column.getElementsByTag("a").first();
                    if (anchorTag != null && anchorTag.text().contains("Attack")) {
                        System.out.println(anchorTag.text());
                        Elements attributeSiblings = column.siblingElements();
                        for (Element attributeSibling : attributeSiblings) {
                            System.out.println(attributeSibling.text());
    
                        }
    
                    }
                }
            }
        }
    }
    

    攻击

    15 99 200,000,000

    【讨论】:

    • 谢谢,这帮了很大的忙,但是我怎么能把每一个都声明为一个字符串,所以字符串等级是 15,字符串级别是 99,字符串 XP 是 200,000,000?
    • 如果使用选择器,则无需嵌套 for 循环。
    猜你喜欢
    • 1970-01-01
    • 2016-09-14
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多