0
我最近編寫了一個小爬蟲,用來搜索任何頁面上的鏈接,並寫入一個文件。我在集合(HashSet)中添加了代碼以避免相同的鏈接...從Set(Crawler,Jsoup,Java)寫一個文件
但由於某種原因代碼不起作用,而且我看到很多重複的文件。
你能幫助修復它中的錯誤嗎?
這裏是履帶式的代碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Crawler {
public static void main(String[] args) {
Set<String> setUrlBase = new HashSet<String>();
Document doc;
String BaseUrlTxtT = "C://Search/urlw.txt";
try {
doc = Jsoup.connect("http://stackoverflow.com/").get();
Elements links = doc.select("a[href]");
for (Element link : links) {
String UrlLinkHref = link.attr("href");
if (UrlLinkHref.indexOf("http://") == 0) {
setUrlBase.add(UrlLinkHref);
for (String strUrlHash : setUrlBase) {
writeToBase(BaseUrlTxtT, strUrlHash + "\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeToBase(String fileName, String text) {
File file = new File(fileName);
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter wr = new FileWriter(file.getAbsoluteFile(), true);
try {
wr.write(text + "\n");
} finally {
wr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
謝謝!你能幫助另一個問題,我認爲每個引用文件是一個新行,但事實證明,在同一行上的幾個鏈接,我想看到一個鏈接到一行.. – user3384347
@ user3384347檢查我的最後編輯,尤其是關於行分隔符的點。 – Pshemo
謝謝你超級!)) – user3384347