Java - 在网站中搜索数据

7

我是Java的新手,遇到了一些问题。

主要想法是连接到一个网站,收集信息并将其存储在数组中。

我想让程序搜索网站找到关键词,并存储关键词后面的内容。

daniweb网站首页底部有一个名为“标签云”的部分,其中包含标签/简短单词

标签云:“我想要存储这里写的内容”

我的想法是首先读取网站的HTML,然后使用Scanner和StringTokenizer搜索该文件以查找关键词后跟文本,然后存储为数组。

是否有更好/更容易的方法?

您建议我在哪里寻找一些示例?

以下是我目前的进展。

import java.net.*;
import java.io.*;

public class URLReader {

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

        URL dweb = new URL("http://www.daniweb.com/");
        URLConnection dw = dweb.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(hc.getInputStream()));
        System.out.println("connected to daniweb");
        String inputLine;

        PrintStream out = new PrintStream(new FileOutputStream("OutFile.txt"));

        try {
        while ((inputLine = in.readLine()) != null)
            out.println(inputLine);

            //System.out.println(inputLine);
            //in.close();
        out.close();
        System.out.println("printed text to outfile");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            Scanner scan = new Scanner(OutFile.txt);
            String search = txtSearch.getText();
            while (scan.hasNextLine()) {
                line = scan.nextLine();
            //still working
                while (st.hasMoreTokens()) {
                    word = st.nextToken();
                    if (word == search) {

                    } else {

                    }
                }
            }
            scan.close();
            SearchWin.dispose();
        } catch (IOException iox) {
        }
    }

任何帮助都将不胜感激!
2个回答

6
我推荐使用jsoup。它可以为您检索和解析页面。
在daniweb上,每个标签云链接都有CSS类tagcloudlink。所以你只需要告诉jsoup提取所有具有类tagcloudlink的标签中的文本。
这是我从jsoup网站上获取的一些帮助,结合我的经验,我没有测试过,但应该能帮助您入门。
List<String> tags = new ArrayList<String>();
Document doc = Jsoup.connect("http://daniweb.com/").get();
Elements taglinks = doc.select("a.tagcloudlink");
for (Element link : taglinks) {
    tags.add(link.text());
}

1
你可以使用 HTML 解析器来完成这个任务。这里有一个链接:HTML 解析器。另外一个我经常使用并且喜欢的是 Jericho HTML 解析器。这里是链接:Jericho HTML 解析器

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接