我是
java新手并遇到一些问题.
主要思想是连接到一个网站并从中收集信息并将其存储在一个数组中.
我希望程序做的是搜索网站找到一个关键词,并存储关键词之后的内容.
在网站底部daniweb的首页上有一个名为“Tag Cloud”的部分,里面标有标签/短字
标签云:“我想存储这里写的东西”
我的想法是首先阅读网站的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) {
- }
- }
任何帮助都将非常感谢!
解决方法
我推荐
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());
- }