更新時間:2022-11-18 14:49:15 來源:動力節點 瀏覽1625次
我們將構建一個使用 BFS 算法遍歷網頁的網絡爬蟲。
爬蟲將從訪問包含的每個 URL 的源 URL 開始。訪問此源 URL 中的每個 URL 后,該算法將訪問子 URL 中的每個 URL 并向下訪問鏈,直到它到達您將指定的斷點。
該算法將僅訪問以前未訪問過的 URL,以確保我們不會循環訪問。這些 URL 代表頂點,URL 之間的連接是邊。
首先將根 URL 添加到隊列和已訪問 URL 列表。
當隊列不為空時,從隊列中刪除 URL 并讀取其原始 HTML 內容。
在讀取 URL 的 HTML 內容時,搜索父 HTML 中包含的任何其他 URL。
當找到新的 URL 時,通過檢查已訪問的 URL 列表來驗證它以前沒有被訪問過。
將新找到的未訪問 URL 添加到隊列和已訪問 URL 列表中。
對在 HTML 內容中找到的每個新 URL 重復步驟 4 和 5。
找到 HTML 中的所有 URL 后,從步驟 2 開始重復,直到程序到達您指定的斷點。
使用名稱創建一個 Java 類WebCrawler并將以下代碼添加到文件中:
public class WebCrawler {
private Queue<String> urlQueue;
private List<String> visitedURLs;
public WebCrawler() {
urlQueue = new LinkedList<>();
visitedURLs = new ArrayList<>();
}
}
在上面的代碼中,我們已經初始化了我們隨后將要使用的類、數據結構和構造函數。
public void crawl(String rootURL, int breakpoint) {
urlQueue.add(rootURL);
visitedURLs.add(rootURL);
while(!urlQueue.isEmpty()){
// remove the next url string from the queue to begin traverse.
String s = urlQueue.remove();
String rawHTML = "";
try{
// create url with the string.
URL url = new URL(s);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine = in.readLine();
// read every line of the HTML content in the URL
// and concat each line to the rawHTML string until every line is read.
while(inputLine != null){
rawHTML += inputLine;
inputLine = in.readLine();
}
in.close();
} catch (Exception e){
e.printStackTrace();
}
// create a regex pattern matching a URL
// that will validate the content of HTML in search of a URL.
String urlPattern = "(www|http:|https:)+[^\s]+[\\w]";
Pattern pattern = Pattern.compile(urlPattern);
Matcher matcher = pattern.matcher(rawHTML);
// Each time the regex matches a URL in the HTML,
// add it to the queue for the next traverse and the list of visited URLs.
breakpoint = getBreakpoint(breakpoint, matcher);
// exit the outermost loop if it reaches the breakpoint.
if(breakpoint == 0){
break;
}
}
}
在該crawl()方法中,rootURL是爬蟲的起點,breakpoint代表您希望爬蟲發現多少個 URL。
該算法涉及的步驟是:
該算法首先將根 URL 添加到隊列和已訪問 URL 列表。
BufferedReader它使用API讀取 URL 的每一行 HTML 內容。
然后,它在讀取rawHTML變量時連接每個 HTML 行。
private int getBreakpoint(int breakpoint, Matcher matcher) {
while(matcher.find()){
String actualURL = matcher.group();
if(!visitedURLs.contains(actualURL)){
visitedURLs.add(actualURL);
System.out.println("Website found with URL " + actualURL);
urlQueue.add(actualURL);
}
// exit the loop if it reaches the breakpoint.
if(breakpoint == 0){
break;
}
breakpoint--;
}
return breakpoint;
}
上面的代碼執行以下操作:
該getBreakPoint方法使用指定的正則表達式模式來發現rawHTML.
這些操作會不斷迭代,直到爬蟲發現了您的breakpoint.
以下是應用程序主要方法的片段:
public static void main(String[] args) {
WebCrawler crawler = new WebCrawler();
String rootURL = "https://www.section.io/engineering-education/springboot-antmatchers/";
crawler.crawl(rootURL, 100);
}
下面是運行該程序的輸出快照:
上面快照中的 URL 是網絡爬蟲從根 URL 開始通過嵌入 URL 爬取到斷點的所有網頁中包含的一些 URL。如果大家想了解更多相關知識,不妨來關注一下本站的Java在線學習,里面的課程內容從入門到精通,細致全面,通俗易懂,很適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習