我正在開發包含網站解析器的第一個項目。我試圖瞭解解析器一點點,跨越了一個名爲「Jsoup」庫發現這裏偶然發現: http://jsoup.org/download將分析後的文本添加到字符串中
然後我嘗試這種代碼示例,我在教程的網站上找到:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HTMLParserExample1 {
public static void main(String[] args) {
Document doc;
try {
// need http protocol
doc = Jsoup.connect("http://google.com").get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
代碼所以我決定嘗試將它與我的其他應用程序(這是一個帶有文本框的JFrame)結合起來
所以我試圖做的是把什麼放在[code] System.out中。 println(); [/ code]裏面的一個字符串。 雖然這樣做我是得到錯誤當我試圖做到這一點的方式如下:
s + "\nlink : " + link.attr("href");
s + "text : " + link.text();
我得到錯誤,並很快意識到這wasnt做的正確的方式,讓我找到了方法String.concat並決定使用它。 使用此之後它仍然沒有工作,我隨後也意識到,什麼也應停止解析被打印出來與System.out的命令..
這裏是我當前的代碼:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JParser {
private String finishedParse;
public static void JParser() {
//String that should hold the finished parse
String finishedParse = new String();
//test string used to see if what the Netbeans IDE recomended me to do work
String tester = new String();
finishedParse = "";
Document doc;
try {
//Need http protocol
doc = Jsoup.connect("http://google.com").get();
//Get page title
String title = doc.title();
System.out.println("title : " + title);
//Get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
//Get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
tester = finishedParse.concat("\nlink : " + link.attr("href"));
tester = finishedParse.concat("text : " + link.text());
tester = finishedParse.concat("\n");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
}
}
//The method i wish to call from my other class to get the parsed text returned.
public String getParsedText(String parsedText){
parsedText = finishedParse;
return parsedText;
}
}
問題現在是應該用System.out命令打印的內容沒有被打印出來,而且我還沒有弄清楚如何將解析後的文本放到我的字符串中。
我真的很想學習,我很難找到我的代碼是錯誤的。我確實在網上搜索回答,但沒有成功。
的錯誤剩下的就是以下 兩個System.out的語句沒有打印出任何東西到控制檯,它沒有工作時,我複製從教程中的代碼。這兩個代碼在上面的帖子中,請閱讀並幫助我。
的問題是,我叫在陌生的路上類,我最好的猜測是,我累了昨天,所以我的無知踢..
1)你提到的錯誤,但你不告訴我們它們是什麼。 2)只需使用+運算符進行字符串連接。 – Aurand 2013-04-11 19:27:57
林將編輯帖子,幷包括更明確的確切問題。 – Rakso 2013-04-11 19:28:55